home *** CD-ROM | disk | FTP | other *** search
/ SGI Freeware 1999 August / SGI Freeware 1999 August.iso / dist / fw_xemacs.idb / usr / freeware / lib / xemacs-20.4 / lisp / comint / comint.el.z / comint.el
Encoding:
Text File  |  1998-05-21  |  114.5 KB  |  2,848 lines

  1. ;;; comint.el --- general command interpreter in a window stuff
  2.  
  3. ;; Copyright (C) 1988, 90, 92, 93, 94, 95 Free Software Foundation, Inc.
  4.  
  5. ;; Author: Olin Shivers <shivers@cs.cmu.edu>
  6. ;; Adapted-by: Simon Marshall <simon@gnu.ai.mit.edu>
  7. ;; Keywords: processes
  8.  
  9. ;; This file is part of XEmacs.
  10.  
  11. ;; XEmacs is free software; you can redistribute it and/or modify it
  12. ;; under the terms of the GNU General Public License as published by
  13. ;; the Free Software Foundation; either version 2, or (at your option)
  14. ;; any later version.
  15.  
  16. ;; XEmacs is distributed in the hope that it will be useful, but
  17. ;; WITHOUT ANY WARRANTY; without even the implied warranty of
  18. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  19. ;; General Public License for more details.
  20.  
  21. ;; You should have received a copy of the GNU General Public License
  22. ;; along with XEmacs; see the file COPYING.  If not, write to the 
  23. ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  24. ;; Boston, MA 02111-1307, USA.
  25.  
  26. ;;; Synched up with: FSF 19.30.
  27.  
  28. ;;; Commentary:
  29.  
  30. ;;; Please send me bug reports, bug fixes, and extensions, so that I can
  31. ;;; merge them into the master source.
  32. ;;;     - Olin Shivers (shivers@cs.cmu.edu)
  33. ;;;     - Simon Marshall (simon@gnu.ai.mit.edu)
  34.  
  35. ;;; This file defines a general command-interpreter-in-a-buffer package
  36. ;;; (comint mode). The idea is that you can build specific process-in-a-buffer
  37. ;;; modes on top of comint mode -- e.g., lisp, shell, scheme, T, soar, ....
  38. ;;; This way, all these specific packages share a common base functionality,
  39. ;;; and a common set of bindings, which makes them easier to use (and
  40. ;;; saves code, implementation time, etc., etc.).
  41.  
  42. ;;; Several packages are already defined using comint mode:
  43. ;;; - shell.el defines a shell-in-a-buffer mode.
  44. ;;; - cmulisp.el defines a simple lisp-in-a-buffer mode.
  45. ;;;
  46. ;;; - The file cmuscheme.el defines a scheme-in-a-buffer mode.
  47. ;;; - The file tea.el tunes scheme and inferior-scheme modes for T.
  48. ;;; - The file soar.el tunes lisp and inferior-lisp modes for Soar.
  49. ;;; - cmutex.el defines tex and latex modes that invoke tex, latex, bibtex,
  50. ;;;   previewers, and printers from within emacs.
  51. ;;; - background.el allows csh-like job control inside emacs.
  52. ;;; It is pretty easy to make new derived modes for other processes.
  53.  
  54. ;;; For documentation on the functionality provided by comint mode, and
  55. ;;; the hooks available for customising it, see the comments below.
  56. ;;; For further information on the standard derived modes (shell,
  57. ;;; inferior-lisp, inferior-scheme, ...), see the relevant source files.
  58.  
  59. ;;; For hints on converting existing process modes (e.g., tex-mode,
  60. ;;; background, dbx, gdb, kermit, prolog, telnet) to use comint-mode
  61. ;;; instead of shell-mode, see the notes at the end of this file.
  62.  
  63.  
  64. ;;; Brief Command Documentation:
  65. ;;;============================================================================
  66. ;;; Comint Mode Commands: (common to all derived modes, like shell & cmulisp
  67. ;;; mode)
  68. ;;;
  69. ;;; XEmacs - FSF19 binds M-p/M-n to comint-{previous,next}-input instead of
  70. ;;;         comint-{previous,next}-matching-input-from-input.
  71. ;;;         XEmacs is mo' better.
  72. ;;;
  73. ;;;
  74. ;;; m-p        comint-previous-matching-input-from-input Cycle backwards in input history
  75. ;;; m-n        comint-next-matching-input-from-input Cycle forwards
  76. ;;; m-r     comint-previous-matching-input   Previous input matching a regexp
  77. ;;; m-s     comint-next-matching-input       Next input that matches
  78. ;;; XEmacs - remove evil binding of M-C-l.  It's already bound to C-c C-r.
  79. ;;; NOT: m-c-l   comint-show-output        Show last batch of process output
  80. ;;; m-c-r   comint-previous-input-matching  Search backwards in input history
  81. ;;; return  comint-send-input
  82. ;;; XEmacs - fsf nuked the binding for ^A, and we nuked the binding for ^D
  83. ;;; c-a     comint-bol                      Beginning of line; skip prompt
  84. ;;; NOT: c-d        comint-delchar-or-maybe-eof     Delete char unless at end of buff
  85. ;;; c-c c-a comint-bol                      Beginning of line; skip prompt
  86. ;;; c-c c-d comint-send-eof                ^d
  87. ;;; c-c c-u comint-kill-input                ^u
  88. ;;; c-c c-w backward-kill-word            ^w
  89. ;;; c-c c-c comint-interrupt-subjob         ^c
  90. ;;; c-c c-z comint-stop-subjob                ^z
  91. ;;; c-c c-\ comint-quit-subjob                ^\
  92. ;;; c-c c-o comint-kill-output            Delete last batch of process output
  93. ;;; c-c c-r comint-show-output            Show last batch of process output
  94. ;;; c-c c-l comint-dynamic-list-input-ring  List input history
  95. ;;;
  96. ;;; Not bound by default in comint-mode (some are in shell mode)
  97. ;;; comint-run                Run a program under comint-mode
  98. ;;; send-invisible            Read a line w/o echo, and send to proc
  99. ;;; comint-dynamic-complete-filename    Complete filename at point.
  100. ;;; comint-dynamic-complete-variable    Complete variable name at point.
  101. ;;; comint-dynamic-list-filename-completions List completions in help buffer.
  102. ;;; comint-replace-by-expanded-filename    Expand and complete filename at point;
  103. ;;;                    replace with expanded/completed name.
  104. ;;; comint-replace-by-expanded-history    Expand history at point;
  105. ;;;                    replace with expanded name.
  106. ;;; comint-magic-space                  Expand history and add (a) space(s).
  107. ;;; comint-kill-subjob            No mercy.
  108. ;;; comint-show-maximum-output          Show as much output as possible.
  109. ;;; comint-continue-subjob        Send CONT signal to buffer's process
  110. ;;;                    group. Useful if you accidentally
  111. ;;;                    suspend your process (with C-c C-z).
  112.  
  113. ;;; comint-mode-hook is the comint mode hook. Basically for your keybindings.
  114.  
  115. ;;; Code:
  116.  
  117. (require 'ring)
  118.  
  119. ;;; Buffer Local Variables:
  120. ;;;============================================================================
  121. ;;; Comint mode buffer local variables:
  122. ;;;     comint-prompt-regexp    - string       comint-bol uses to match prompt
  123. ;;;     comint-delimiter-argument-list - list  For delimiters and arguments
  124. ;;;     comint-last-input-start - marker       Handy if inferior always echoes
  125. ;;;     comint-last-input-end   - marker       For comint-kill-output command
  126. ;;;     comint-input-ring-size  - integer      For the input history
  127. ;;;     comint-input-ring       - ring             mechanism
  128. ;;;     comint-input-ring-index - number           ...
  129. ;;;     comint-input-autoexpand - symbol           ...
  130. ;;;     comint-input-ignoredups - boolean          ...
  131. ;;;     comint-last-input-match - string           ...
  132. ;;;     comint-dynamic-complete-functions - hook   For the completion mechanism
  133. ;;;     comint-completion-fignore - list           ...
  134. ;;;    comint-file-name-quote-list - list       ...
  135. ;;;     comint-get-old-input    - function     Hooks for specific 
  136. ;;;     comint-input-filter-functions - hook     process-in-a-buffer
  137. ;;;     comint-output-filter-functions - hook    function modes.
  138. ;;;     comint-input-filter     - function         ...
  139. ;;;     comint-input-sender    - function         ...
  140. ;;;     comint-eol-on-send    - boolean          ...
  141. ;;;     comint-process-echoes   - boolean          ...
  142. ;;;     comint-scroll-to-bottom-on-input - symbol For scroll behavior
  143. ;;;     comint-scroll-to-bottom-on-output - symbol ...
  144. ;;;     comint-scroll-show-maximum-output - boolean...
  145. ;;;
  146. ;;; Comint mode non-buffer local variables:
  147. ;;;     comint-completion-addsuffix - boolean/cons  For file name completion
  148. ;;;     comint-completion-autolist  - boolean      behavior
  149. ;;;     comint-completion-recexact  - boolean      ...
  150.  
  151. (require 'easymenu)
  152.  
  153. (defgroup comint nil
  154.   "General command interpreter in a window stuff."
  155.   :group 'processes)
  156.  
  157. (defgroup comint-completion nil
  158.   "Completion facilities in comint"
  159.   :group 'comint)
  160.  
  161. (defgroup comint-source nil
  162.   "Source finding facilities in comint"
  163.   :prefix "comint-"
  164.   :group 'comint)
  165.  
  166.  
  167. (defvar comint-prompt-regexp "^"
  168.   "Regexp to recognise prompts in the inferior process.
  169. Defaults to \"^\", the null string at BOL.
  170.  
  171. Good choices:
  172.   Canonical Lisp: \"^[^> \\n]*>+:? *\" (Lucid, franz, kcl, T, cscheme, oaklisp)
  173.   Lucid Common Lisp: \"^\\\\(>\\\\|\\\\(->\\\\)+\\\\) *\"
  174.   franz: \"^\\\\(->\\\\|<[0-9]*>:\\\\) *\"
  175.   kcl: \"^>+ *\"
  176.   shell: \"^[^#$%>\\n]*[#$%>] *\"
  177.   T: \"^>+ *\"
  178.  
  179. The pattern should begin with \"^\".  It can match text on more than one line.
  180. This pattern gets handed to re-search-backward, not looking-at.
  181.  
  182. This is a good thing to set in mode hooks.")
  183.  
  184. (defvar comint-delimiter-argument-list ()
  185.   "List of characters to recognise as separate arguments in input.
  186. Strings comprising a character in this list will separate the arguments
  187. surrounding them, and also be regarded as arguments in their own right (unlike
  188. whitespace).  See `comint-arguments'.
  189. Defaults to the empty list.
  190.  
  191. For shells, a good value is (?\\| ?& ?< ?> ?\\( ?\\) ?;).
  192.  
  193. This is a good thing to set in mode hooks.")
  194.  
  195. ;; #### BUG: this loser mangles history; when one types
  196. ;;        find /tmp \( -name foo \) -print
  197. ;; one gets    find /tmp \ ( -name foo \ ) -print
  198. ;;
  199. ;; XEmacs - So turn this off by default.  -- jwz
  200. ;;
  201. (defcustom comint-input-autoexpand nil
  202.   "*If non-nil, expand input command history references on completion.
  203. This mirrors the optional behavior of tcsh (its autoexpand and histlit).
  204.  
  205. If the value is `input', then the expansion is seen on input.
  206. If the value is `history', then the expansion is only when inserting
  207. into the buffer's input ring.  See also `comint-magic-space' and
  208. `comint-dynamic-complete'.
  209.  
  210. This variable is buffer-local."
  211.   :type '(choice (const :tag "off" nil)
  212.          (const :tag "on" t)
  213.          (const input)
  214.          (const history))
  215.   :group 'comint)
  216.  
  217. ;; XEmacs - this should default to t for consistency with minibuffer history. -jwz
  218. (defcustom comint-input-ignoredups t
  219.   "*If non-nil, don't add input matching the last on the input ring.
  220. This mirrors the optional behavior of bash.
  221.  
  222. This variable is buffer-local."
  223.   :type 'boolean
  224.   :group 'comint)
  225.  
  226. (defcustom comint-input-ring-file-name nil
  227.   "*If non-nil, name of the file to read/write input history.
  228. See also `comint-read-input-ring' and `comint-write-input-ring'.
  229.  
  230. This variable is buffer-local, and is a good thing to set in mode hooks."
  231.   :type 'boolean
  232.   :group 'comint)
  233.  
  234. (defcustom comint-scroll-to-bottom-on-input nil
  235.   "*Controls whether input to interpreter causes window to scroll.
  236. If nil, then do not scroll.  If t or `all', scroll all windows showing buffer.
  237. If `this', scroll only the selected window.
  238.  
  239. The default is nil.
  240.  
  241. See `comint-preinput-scroll-to-bottom'.  This variable is buffer-local."
  242.   :type '(choice (const :tag "off" nil)
  243.          (const t)
  244.          (const all)
  245.          (const this))
  246.   :group 'comint)
  247.  
  248. (defcustom comint-scroll-to-bottom-on-output nil
  249.   "*Controls whether interpreter output causes window to scroll.
  250. If nil, then do not scroll.  If t or `all', scroll all windows showing buffer.
  251. If `this', scroll only the selected window.
  252. If `others', scroll only those that are not the selected window.
  253.  
  254. The default is nil.
  255.  
  256. See variable `comint-scroll-show-maximum-output' and function
  257. `comint-postoutput-scroll-to-bottom'.  This variable is buffer-local."
  258.   :type '(choice (const :tag "off" nil)
  259.          (const t)
  260.          (const all)
  261.          (const this)
  262.          (const others))
  263.   :group 'comint)
  264.  
  265. ;; XEmacs - Default this to nil: this is just horrible
  266. (defcustom comint-scroll-show-maximum-output nil
  267.   "*Controls how interpreter output causes window to scroll.
  268. If non-nil, then show the maximum output when the window is scrolled.
  269.  
  270. See variable `comint-scroll-to-bottom-on-output' and function
  271. `comint-postoutput-scroll-to-bottom'.  This variable is buffer-local."
  272.   :type 'boolean
  273.   :group 'comint)
  274.  
  275. (defcustom comint-buffer-maximum-size 1024
  276.   "*The maximum size in lines for comint buffers.
  277. Comint buffers are truncated from the top to be no greater than this number, if
  278. the function `comint-truncate-buffer' is on `comint-output-filter-functions'."
  279.   :type 'integer
  280.   :group 'comint)
  281.  
  282. (defvar comint-input-ring-size 32
  283.   "Size of input history ring.")
  284.  
  285. (defcustom comint-process-echoes nil
  286.   "*If non-nil, assume that the subprocess echoes any input.
  287. If so, delete one copy of the input so that only one copy eventually
  288. appears in the buffer.
  289.  
  290. This variable is buffer-local."
  291.   :type 'boolean
  292.   :group 'comint)
  293.  
  294. ;; AIX puts the name of the person being su'd to in from of the prompt.
  295. (defcustom comint-password-prompt-regexp
  296.   (if (eq system-type 'aix-v3)
  297.       "\\(\\([Oo]ld \\|[Nn]ew \\|^\\|^..*s\\)[Pp]assword\\|pass phrase\\):\\s *\\'"
  298.   "\\(\\([Oo]ld \\|[Nn]ew \\|^\\)[Pp]assword\\|pass phrase\\):\\s *\\'")
  299.   "*Regexp matching prompts for passwords in the inferior process.
  300. This is used by `comint-watch-for-password-prompt'."
  301.   :type 'regexp
  302.   :group 'comint)
  303.  
  304. ;;; Here are the per-interpreter hooks.
  305. (defvar comint-get-old-input (function comint-get-old-input-default)
  306.   "Function that returns old text in comint mode.
  307. This function is called when return is typed while the point is in old text.
  308. It returns the text to be submitted as process input.  The default is
  309. `comint-get-old-input-default', which grabs the current line, and strips off
  310. leading text matching `comint-prompt-regexp'.")
  311.  
  312. ;; XEmacs - fsf doesn't have this, and I think it ought to default to 't'
  313. ;; because it's good idiot-proof interface.  --stig
  314. (defcustom comint-append-old-input t
  315.   "*If nil, old text selected by \\[comint-send-input] is re-sent immediately.
  316. If non-nil, the old text is appended to the end of the buffer,
  317. and a prompting message is printed.
  318.  
  319. This flag does not affect the behavior of \\[comint-send-input]
  320. after the process output mark."
  321.   :type 'boolean
  322.   :group 'comint)
  323.  
  324. (defvar comint-dynamic-complete-functions
  325.   '(comint-replace-by-expanded-history comint-dynamic-complete-filename)
  326.   "List of functions called to perform completion.
  327. Functions should return non-nil if completion was performed.
  328. See also `comint-dynamic-complete'.
  329.  
  330. This is a good thing to set in mode hooks.")
  331.  
  332. (defvar comint-input-filter
  333.   #'(lambda (str)
  334.       (and (not (string-match "\\`\\s *\\'" str))
  335.            ;; XEmacs - ignore '!!' and kin
  336.            (> (length str) 2)))
  337.   "Predicate for filtering additions to input history.
  338. Takes one argument, the input.  If non-nil, the input may be saved on the input
  339. history list.  Default is to save anything longer than two characters
  340. that isn't all whitespace.")
  341.  
  342. (defvar comint-input-filter-functions '()
  343.   "Functions to call before input is sent to the process.
  344. These functions get one argument, a string containing the text to send.
  345.  
  346. This variable is buffer-local.")
  347.  
  348. (defvar comint-output-filter-functions '(comint-postoutput-scroll-to-bottom
  349.                      ;; XEmacs - not here by default for FSF
  350.                      comint-watch-for-password-prompt)
  351.   "Functions to call after output is inserted into the buffer.
  352. One possible function is `comint-postoutput-scroll-to-bottom'.
  353. These functions get one argument, a string containing the text just inserted.
  354.  
  355. This variable is buffer-local.")
  356.  
  357. (defvar comint-input-sender (function comint-simple-send)
  358.   "Function to actually send to PROCESS the STRING submitted by user.
  359. Usually this is just `comint-simple-send', but if your mode needs to
  360. massage the input string, put a different function here.
  361. `comint-simple-send' just sends the string plus a newline.
  362. This is called from the user command `comint-send-input'.")
  363.  
  364. (defcustom comint-eol-on-send t
  365.   "*Non-nil means go to the end of the line before sending input.
  366. See `comint-send-input'."
  367.   :type 'boolean
  368.   :group 'comint)
  369.  
  370. (defcustom comint-mode-hook '()
  371.   "Called upon entry into comint-mode
  372. This is run before the process is cranked up."
  373.   :type 'hook
  374.   :group 'comint)
  375.  
  376. ;; This is initialized by the various language environments, do not
  377. ;; Custom-ize it.
  378. (defvar comint-exec-hook '()
  379.   "Called each time a process is exec'd by `comint-exec'.
  380. This is called after the process is cranked up.  It is useful for things that
  381. must be done each time a process is executed in a comint mode buffer (e.g.,
  382. `(process-kill-without-query)').  In contrast, the `comint-mode-hook' is only
  383. executed once when the buffer is created.")
  384.  
  385. (defvar comint-mode-map nil)
  386.  
  387. (defvar comint-ptyp t
  388.   "Non-nil if communications via pty; false if by pipe.  Buffer local.
  389. This is to work around a bug in Emacs process signalling.")
  390.  
  391. (defvar comint-input-ring nil)
  392. (defvar comint-last-input-start)
  393. (defvar comint-last-input-end)
  394. (defvar comint-last-output-start)
  395. (defvar comint-input-ring-index nil
  396.   "Index of last matched history element.")
  397. (defvar comint-matching-input-from-input-string ""
  398.   "Input previously used to match input history.")
  399.  
  400. (put 'comint-input-ring 'permanent-local t)
  401. (put 'comint-input-ring-index 'permanent-local t)
  402. (put 'comint-input-autoexpand 'permanent-local t)
  403. (put 'comint-input-filter-functions 'permanent-local t)
  404. (put 'comint-output-filter-functions 'permanent-local t)
  405. (put 'comint-scroll-to-bottom-on-input 'permanent-local t)
  406. (put 'comint-scroll-to-bottom-on-output 'permanent-local t)
  407. (put 'comint-scroll-show-maximum-output 'permanent-local t)
  408. (put 'comint-ptyp 'permanent-local t)
  409.  
  410. (defvar comint-1-menubar-menu nil)
  411. (defconst comint-1-menubar-menu-1
  412.   (purecopy
  413.    '("Comint1"
  414.      ["Previous Matching Current Input"
  415.       comint-previous-matching-input-from-input t]
  416.      ["Next Matching Current Input" comint-next-matching-input-from-input t]
  417.      ["Previous Input" comint-previous-input t]
  418.      ["Next Input" comint-next-input t]
  419.      ["Previous Input Matching Regexp..." comint-previous-matching-input t]
  420.      ["Next Input Matching Regexp..." comint-next-matching-input t]
  421.      ["Backward Matching Input..." comint-backward-matching-input t]
  422.      ["Forward Matching Input..." comint-forward-matching-input t]
  423.      "---"
  424.      ["Copy Old Input" comint-copy-old-input t]
  425.      ["Kill Current Input" comint-kill-input t]
  426.      ["Show Current Output Group" comint-show-output t]
  427.      ["Show Maximum Output" comint-show-maximum-output t]
  428.      ["Goto Previous Prompt" comint-previous-prompt t]
  429.      ["Goto Next Prompt" comint-next-prompt t]
  430.      ["Kill Command Output" comint-kill-output t]
  431.      )))
  432.  
  433. (defvar comint-2-menubar-menu nil)
  434. (defconst comint-2-menubar-menu-1
  435.   (purecopy
  436.    '("Comint2"
  437.      ["Complete Before Point" comint-dynamic-complete t]
  438.      ["Complete File Name" comint-dynamic-complete-filename t]
  439.      ["File Completion Listing" comint-dynamic-list-filename-completions t]
  440.      ["Expand File Name" comint-replace-by-expanded-filename t]
  441.      ;; this is cheesy but the easiest way to get this.
  442.      ["Complete Env. Variable Name" shell-dynamic-complete-environment-variable
  443.       :active t :included (eq 'shell-mode major-mode)]
  444.      ["Expand Directory Reference" shell-replace-by-expanded-directory
  445.       :active t :included (eq 'shell-mode major-mode)]
  446.      "---"
  447.      ["Send INT"  comint-interrupt-subjob t]
  448.      ["Send STOP" comint-stop-subjob t]
  449.      ["Send CONT" comint-continue-subjob t]
  450.      ["Send QUIT" comint-quit-subjob t]
  451.      ["Send KILL" comint-kill-subjob t]
  452.      ["Send EOF"  comint-send-eof t]
  453.      )))
  454.  
  455. (defvar comint-history-menubar-menu nil)
  456. (defconst comint-history-menubar-menu-1
  457.   (purecopy
  458.    '("History"
  459.      :filter comint-history-menu-filter
  460.      ["Expand History Before Point" comint-replace-by-expanded-history
  461.                     comint-input-autoexpand]
  462.      ["List Input History" comint-dynamic-list-input-ring t]
  463.      "---"
  464.      )))
  465.  
  466.  
  467. (defun comint-mode ()
  468.   "Major mode for interacting with an inferior interpreter.
  469. Interpreter name is same as buffer name, sans the asterisks.
  470. Return at end of buffer sends line as input.
  471. Return not at end copies rest of line to end and sends it.
  472. Setting variable `comint-eol-on-send' means jump to the end of the line
  473. before submitting new input.
  474.  
  475. This mode is customised to create major modes such as Inferior Lisp
  476. mode, Shell mode, etc.  This can be done by setting the hooks
  477. `comint-input-filter-functions', `comint-input-filter', `comint-input-sender'
  478. and `comint-get-old-input' to appropriate functions, and the variable
  479. `comint-prompt-regexp' to the appropriate regular expression.
  480.  
  481. An input history is maintained of size `comint-input-ring-size', and
  482. can be accessed with the commands \\[comint-next-input], \\[comint-previous-input], and \\[comint-dynamic-list-input-ring].
  483. Input ring history expansion can be achieved with the commands
  484. \\[comint-replace-by-expanded-history] or \\[comint-magic-space].
  485. Input ring expansion is controlled by the variable `comint-input-autoexpand',
  486. and addition is controlled by the variable `comint-input-ignoredups'.
  487.  
  488. Commands with no default key bindings include `send-invisible',
  489. `comint-dynamic-complete', `comint-dynamic-list-filename-completions', and
  490. `comint-magic-space'.
  491.  
  492. Input to, and output from, the subprocess can cause the window to scroll to
  493. the end of the buffer.  See variables `comint-output-filter-functions',
  494. `comint-scroll-to-bottom-on-input', and `comint-scroll-to-bottom-on-output'.
  495.  
  496. If you accidentally suspend your process, use \\[comint-continue-subjob]
  497. to continue it.
  498.  
  499. \\{comint-mode-map}
  500.  
  501. Entry to this mode runs the hooks on `comint-mode-hook'."
  502.   (interactive)
  503.   ;; Do not remove this.  All major modes must do this.
  504.   (kill-all-local-variables)
  505.   (setq major-mode 'comint-mode)
  506.   (setq mode-name "Comint")
  507.   (setq mode-line-process '(": %s")) ; XEmacs
  508.   (use-local-map comint-mode-map)
  509.   (make-local-variable 'comint-last-input-start)
  510.   (setq comint-last-input-start (make-marker))
  511.   (set-marker comint-last-input-start (point-min))
  512.   (make-local-variable 'comint-last-input-end)
  513.   (setq comint-last-input-end (make-marker))
  514.   (set-marker comint-last-input-end (point-min))
  515.   (make-local-variable 'comint-last-output-start)
  516.   (setq comint-last-output-start (make-marker))
  517.   (make-local-variable 'comint-prompt-regexp)        ; Don't set; default
  518.   (make-local-variable 'comint-input-ring-size)      ; ...to global val.
  519.   (make-local-variable 'comint-input-ring)
  520.   (make-local-variable 'comint-input-ring-file-name)
  521.   (or (and (boundp 'comint-input-ring) comint-input-ring)
  522.       (setq comint-input-ring (make-ring comint-input-ring-size)))
  523.   (make-local-variable 'comint-input-ring-index)
  524.   (or (and (boundp 'comint-input-ring-index) comint-input-ring-index)
  525.       (setq comint-input-ring-index nil))
  526.   (make-local-variable 'comint-matching-input-from-input-string)
  527.   (make-local-variable 'comint-input-autoexpand)
  528.   (make-local-variable 'comint-input-ignoredups)
  529.   (make-local-variable 'comint-delimiter-argument-list)
  530.   (make-local-hook 'comint-dynamic-complete-functions)
  531.   (make-local-variable 'comint-completion-fignore)
  532.   (make-local-variable 'comint-get-old-input)
  533.   (make-local-hook 'comint-input-filter-functions)
  534.   (make-local-variable 'comint-input-filter)
  535.   (make-local-variable 'comint-input-sender)
  536.   (make-local-variable 'comint-eol-on-send)
  537.   (make-local-variable 'comint-scroll-to-bottom-on-input)
  538.   (make-local-variable 'comint-scroll-to-bottom-on-output)
  539.   (make-local-variable 'comint-scroll-show-maximum-output)
  540.   (make-local-hook 'pre-command-hook)
  541.   (add-hook 'pre-command-hook 'comint-preinput-scroll-to-bottom nil t)
  542.   (make-local-hook 'comint-output-filter-functions)
  543.   (make-local-variable 'comint-ptyp)
  544.   (make-local-hook 'comint-exec-hook)
  545.   (make-local-variable 'comint-process-echoes)
  546.   (make-local-variable 'comint-file-name-quote-list)
  547.   (if (featurep 'menubar)
  548.       (progn
  549.     ;; make a local copy of the menubar, so our modes don't
  550.     ;; change the global menubar
  551.     ;; (set-buffer-menubar current-menubar)
  552.     ;; (add-submenu nil comint-1-menubar-menu)
  553.     (unless comint-1-menubar-menu
  554.       (easy-menu-define comint-1-menubar-menu nil ""
  555.                 comint-1-menubar-menu-1))
  556.     (easy-menu-add comint-1-menubar-menu)
  557.     ;; (add-submenu nil comint-2-menubar-menu)
  558.     (unless comint-2-menubar-menu
  559.       (easy-menu-define comint-2-menubar-menu nil ""
  560.                 comint-2-menubar-menu-1))
  561.     (easy-menu-add comint-2-menubar-menu)
  562.     ;; (add-submenu nil comint-history-menubar-menu)))
  563.     (unless comint-history-menubar-menu
  564.       (easy-menu-define comint-history-menubar-menu nil ""
  565.                 comint-history-menubar-menu-1))
  566.     (easy-menu-add comint-history-menubar-menu)))
  567.   (run-hooks 'comint-mode-hook))
  568.  
  569. (if comint-mode-map
  570.     nil
  571.   ;; Keys:
  572.   (setq comint-mode-map (make-sparse-keymap))
  573.   (set-keymap-name comint-mode-map 'comint-mode-map) ; XEmacs
  574.  
  575.   ;; XEmacs - The FSF19 party line
  576.   ;;(define-key comint-mode-map "\ep" 'comint-previous-input)
  577.   ;;(define-key comint-mode-map "\en" 'comint-next-input)
  578.  
  579.   ;; The Lucid party line
  580.   (define-key comint-mode-map "\ep" 'comint-previous-matching-input-from-input)
  581.   (define-key comint-mode-map "\en" 'comint-next-matching-input-from-input)
  582.   (define-key comint-mode-map '(control up)
  583.     'comint-previous-matching-input-from-input)
  584.   (define-key comint-mode-map '(control down)
  585.     'comint-next-matching-input-from-input)
  586.  
  587.   (define-key comint-mode-map "\er" 'comint-previous-matching-input)
  588.   (define-key comint-mode-map "\es" 'comint-next-matching-input)
  589.   ;; XEmacs - alt-meta-anything is a horrible binding.  Some keyboards don't have
  590.   ;; meta keys, so we use alt as meta.  Consequently, alt-meta will not exist on
  591.   ;; all keyboards.  Just blow this.  These functions are on M-n and M-p.  --stig
  592.   ;;(define-key comint-mode-map [?\A-\M-r] 'comint-previous-matching-input-from-input)
  593.   ;;(define-key comint-mode-map [?\A-\M-s] 'comint-next-matching-input-from-input)
  594.   ;; XEmacs: Yuck yuck.  C-M-l has a perfectly good normal binding.
  595.   ;;(define-key comint-mode-map "\e\C-l" 'comint-show-output)
  596.   (define-key comint-mode-map "\C-m" 'comint-send-input)
  597.   ;; XEmacs - Use ^C^D instead of ^D.  Jamie & Stig think this is too un-emacs.
  598.   ;;(define-key comint-mode-map "\C-d" 'comint-delchar-or-maybe-eof)
  599.   ;; XEmacs - FSF nuked this, but we're gonna keep it....
  600.   (define-key comint-mode-map "\C-a" 'comint-bol)
  601.   ;; yuck, this is evil.
  602.   ;;(define-key comint-mode-map "\C-u" 'comint-universal-argument) ; XEmacs
  603.   (define-key comint-mode-map "\C-c\C-a" 'comint-bol)
  604.   (define-key comint-mode-map "\C-c\C-u" 'comint-kill-input)
  605.   (define-key comint-mode-map "\C-c\C-w" 'backward-kill-word)
  606.   (define-key comint-mode-map "\C-c\C-c" 'comint-interrupt-subjob)
  607.   (define-key comint-mode-map "\C-c\C-z" 'comint-stop-subjob)
  608.   (define-key comint-mode-map "\C-c\C-\\" 'comint-quit-subjob)
  609.   (define-key comint-mode-map "\C-c\C-m" 'comint-copy-old-input)
  610.   (define-key comint-mode-map "\C-c\C-o" 'comint-kill-output)
  611.   (define-key comint-mode-map "\C-c\C-r" 'comint-show-output)
  612.   (define-key comint-mode-map "\C-c\C-e" 'comint-show-maximum-output)
  613.   (define-key comint-mode-map "\C-c\C-l" 'comint-dynamic-list-input-ring)
  614.   (define-key comint-mode-map "\C-c\C-d" 'comint-send-eof)
  615.  
  616.   (define-key comint-mode-map "\C-c\C-n" 'comint-next-prompt)
  617.   (define-key comint-mode-map "\C-c\C-p" 'comint-previous-prompt)
  618.   ;; John Rose's suggestion
  619.   (define-key comint-mode-map "\e}" 'comint-next-prompt)
  620.   (define-key comint-mode-map "\e{" 'comint-previous-prompt)
  621.  
  622.   #-infodock (define-key comint-mode-map 'button3 'comint-popup-menu)
  623.   )
  624.  
  625. ;;(defconst comint-popup-menu
  626. ;;  '("Command Interpreter Commands"
  627. ;;    ["Kill Command Output" comint-kill-output t]
  628. ;;    ["Goto Next Prompt" comint-next-prompt t]
  629. ;;    ["Goto Previous Prompt" comint-previous-prompt t]
  630. ;;    ["Kill Input" comint-kill-input t]
  631. ;;    "----"
  632. ;;    ["Previous Input" comint-previous-matching-input-from-input t]
  633. ;;    ["Next Input" comint-next-matching-input-from-input t]
  634. ;;    ["Previous Input matching Regexp..." 'comint-previous-matching-input t]
  635. ;;    ["Next Input matching Regexp..." 'comint-next-matching-input t]
  636. ;;    ["List Command History" comint-dynamic-list-input-ring t]
  637. ;;    "----"
  638. ;;    ["Send INT"  comint-interrupt-subjob t]
  639. ;;    ["Send STOP" comint-stop-subjob t]
  640. ;;    ["Send CONT" comint-continue-subjob t]
  641. ;;    ["Send QUIT" comint-quit-subjob t]
  642. ;;    ["Send KILL" comint-kill-subjob t]
  643. ;;    ["Send EOF"  comint-send-eof t]
  644. ;;    ))
  645.  
  646. (defun comint-popup-menu (event)
  647.   "Display the comint-mode menu."
  648.   (interactive "@e")
  649.   (let ((history (comint-make-history-menu)))
  650.     (popup-menu (if history
  651.             (append mode-popup-menu
  652.                 (list "---" (cons "Command History" history)))
  653.           mode-popup-menu))))
  654.  
  655. (defcustom comint-history-menu-max 40
  656.   "*Maximum number of entries to display on the Comint command-history menu."
  657.   :type 'integer
  658.   :group 'comint)
  659.  
  660. (defun comint-history-menu-filter (menu)
  661.   (append menu (comint-make-history-menu)))
  662.  
  663. (defun comint-make-history-menu ()
  664.   (if (or (not (ringp comint-input-ring))
  665.       (ring-empty-p comint-input-ring))
  666.       nil
  667.     (let ((menu nil)
  668.       hist
  669.       (index (1- (ring-length comint-input-ring)))
  670.       (count 0))
  671.       ;; We have to build up a list ourselves from the ring vector.
  672.       ;; We don't want the entries to get translated in a Mule
  673.       ;; environment, so we use the `suffix' field of the menu entries.
  674.       (while (and (>= index 0)
  675.           (and comint-history-menu-max
  676.                (< count comint-history-menu-max)))
  677.     (setq hist (ring-ref comint-input-ring index)
  678.           menu (cons (vector "" (list 'comint-menu-history hist) t hist)
  679.              menu)
  680.           count (1+ count)
  681.           index (1- index)))
  682.       menu)))
  683.  
  684. (defun comint-menu-history (string)
  685.   (goto-char (point-max))
  686.   (delete-region (process-mark (get-buffer-process (current-buffer))) (point))
  687.   (insert string))
  688.  
  689. (defun comint-check-proc (buffer)
  690.   "Return t if there is a living process associated w/buffer BUFFER.
  691. Living means the status is `open', `run', or `stop'.
  692. BUFFER can be either a buffer or the name of one."
  693.   (let ((proc (get-buffer-process buffer)))
  694.     (and proc (memq (process-status proc) '(open run stop)))))
  695.  
  696. ;;; Note that this guy, unlike shell.el's make-shell, barfs if you pass it ()
  697. ;;; for the second argument (program).
  698. ;;;###autoload
  699. (defun make-comint (name program &optional startfile &rest switches)
  700.   "Make a comint process NAME in a buffer, running PROGRAM.
  701. The name of the buffer is made by surrounding NAME with `*'s.
  702. PROGRAM should be either a string denoting an executable program to create
  703. via `start-process', or a cons pair of the form (HOST . SERVICE) denoting a TCP
  704. connection to be opened via `open-network-stream'.  If there is already a
  705. running process in that buffer, it is not restarted.  Optional third arg
  706. STARTFILE is the name of a file to send the contents of to the process.
  707.  
  708. If PROGRAM is a string, any more args are arguments to PROGRAM."
  709.   (or (fboundp 'start-process)
  710.       (error "Multiple processes are not supported for this system"))
  711.   (let ((buffer (get-buffer-create (concat "*" name "*"))))
  712.     ;; If no process, or nuked process, crank up a new one and put buffer in
  713.     ;; comint mode.  Otherwise, leave buffer and existing process alone.
  714.     (cond ((not (comint-check-proc buffer))
  715.        (save-excursion
  716.          (set-buffer buffer)
  717.          (comint-mode)) ; Install local vars, mode, keymap, ...
  718.        (comint-exec buffer name program startfile switches)))
  719.     buffer))
  720.  
  721. ;;;###autoload
  722. (defun comint-run (program)
  723.   "Run PROGRAM in a comint buffer and switch to it.
  724. The buffer name is made by surrounding the file name of PROGRAM with `*'s.
  725. The file name is used to make a symbol name, such as `comint-sh-hook', and any
  726. hooks on this symbol are run in the buffer.
  727. See `make-comint' and `comint-exec'."
  728.   (interactive "sRun program: ")
  729.   (let ((name (file-name-nondirectory program)))
  730.     (switch-to-buffer (make-comint name program))
  731.     (run-hooks (intern-soft (concat "comint-" name "-hook")))))
  732.  
  733. (defun comint-exec (buffer name command startfile switches)
  734.   "Start up a process in buffer BUFFER for comint modes.
  735. Blasts any old process running in the buffer.  Doesn't set the buffer mode.
  736. You can use this to cheaply run a series of processes in the same comint
  737. buffer.  The hook `comint-exec-hook' is run after each exec."
  738.   (save-excursion
  739.     (set-buffer buffer)
  740.     (let ((proc (get-buffer-process buffer)))    ; Blast any old process.
  741.       (if proc (delete-process proc)))
  742.     ;; Crank up a new process
  743.     (let ((proc
  744.        (if (consp command)
  745.            (open-network-stream name buffer (car command) (cdr command))
  746.          (comint-exec-1 name buffer command switches))))
  747.       (set-process-filter proc 'comint-output-filter)
  748.       (make-local-variable 'comint-ptyp)
  749.       (setq comint-ptyp process-connection-type) ; T if pty, NIL if pipe.
  750.       ;; Jump to the end, and set the process mark.
  751.       (goto-char (point-max))
  752.       (set-marker (process-mark proc) (point))
  753.       ;; Feed it the startfile.
  754.       (cond (startfile
  755.          ;;This is guaranteed to wait long enough
  756.          ;;but has bad results if the comint does not prompt at all
  757.          ;;         (while (= size (buffer-size))
  758.          ;;           (sleep-for 1))
  759.          ;;I hope 1 second is enough!
  760.          (sleep-for 1)
  761.          (goto-char (point-max))
  762.          (insert-file-contents startfile)
  763.          (setq startfile (buffer-substring (point) (point-max)))
  764.          (delete-region (point) (point-max))
  765.          (comint-send-string proc startfile)))
  766.     (run-hooks 'comint-exec-hook)
  767.     buffer)))
  768.  
  769. ;;; This auxiliary function cranks up the process for comint-exec in
  770. ;;; the appropriate environment.
  771.  
  772. (defun comint-exec-1 (name buffer command switches)
  773.   (let ((process-environment
  774.      (nconc
  775.       ;; If using termcap, we specify `emacs' as the terminal type
  776.       ;; because that lets us specify a width.
  777.       ;; If using terminfo, we specify `unknown' because that is
  778.       ;; a defined terminal type.  `emacs' is not a defined terminal type
  779.       ;; and there is no way for us to define it here.
  780.       ;; Some programs that use terminfo get very confused
  781.       ;; if TERM is not a valid terminal type.
  782.       (if (and (boundp 'system-uses-terminfo) system-uses-terminfo)
  783.           (list "TERM=unknown"
  784.             (format "COLUMNS=%d" (frame-width)))
  785.         (list "TERM=emacs"
  786.           (format "TERMCAP=emacs:co#%d:tc=unknown:" (frame-width))))
  787.       (if (getenv "EMACS") nil (list "EMACS=t"))
  788.       process-environment))
  789.     (default-directory
  790.       (if (file-directory-p default-directory)
  791.           default-directory
  792.         "/")))
  793.     (apply 'start-process name buffer command switches)))
  794.  
  795. ;;; Input history processing in a buffer
  796. ;;; ===========================================================================
  797. ;;; Useful input history functions, courtesy of the Ergo group.
  798.  
  799. ;;; Eleven commands:
  800. ;;; comint-dynamic-list-input-ring    List history in help buffer.
  801. ;;; comint-previous-input        Previous input...
  802. ;;; comint-previous-matching-input    ...matching a string.
  803. ;;; comint-previous-matching-input-from-input ... matching the current input.
  804. ;;; comint-next-input            Next input...
  805. ;;; comint-next-matching-input        ...matching a string.
  806. ;;; comint-next-matching-input-from-input     ... matching the current input.
  807. ;;; comint-backward-matching-input      Backwards input...
  808. ;;; comint-forward-matching-input       ...matching a string.
  809. ;;; comint-replace-by-expanded-history    Expand history at point;
  810. ;;;                    replace with expanded history.
  811. ;;; comint-magic-space            Expand history and insert space.
  812. ;;;
  813. ;;; Three functions:
  814. ;;; comint-read-input-ring              Read into comint-input-ring...
  815. ;;; comint-write-input-ring             Write to comint-input-ring-file-name.
  816. ;;; comint-replace-by-expanded-history-before-point Workhorse function.
  817.  
  818. (defun comint-read-input-ring (&optional silent)
  819.   "Sets the buffer's `comint-input-ring' from a history file.
  820. The name of the file is given by the variable `comint-input-ring-file-name'.
  821. The history ring is of size `comint-input-ring-size', regardless of file size.
  822. If `comint-input-ring-file-name' is nil this function does nothing.
  823.  
  824. If the optional argument SILENT is non-nil, we say nothing about a
  825. failure to read the history file.
  826.  
  827. This function is useful for major mode commands and mode hooks.
  828.  
  829. The structure of the history file should be one input command per line,
  830. with the most recent command last.
  831. See also `comint-input-ignoredups' and `comint-write-input-ring'."
  832.   (cond ((or (null comint-input-ring-file-name)
  833.          (equal comint-input-ring-file-name ""))
  834.      nil)
  835.     ((not (file-readable-p comint-input-ring-file-name))
  836.      (or silent
  837.          (message "Cannot read history file %s"
  838.               comint-input-ring-file-name)))
  839.     (t
  840.      (let ((history-buf (get-buffer-create " *comint-history*"))
  841.            (file comint-input-ring-file-name)
  842.            (count 0)
  843.            (ring (make-ring comint-input-ring-size)))
  844.        (unwind-protect
  845.            (save-excursion
  846.          (set-buffer history-buf)
  847.          (widen)
  848.          (erase-buffer)
  849.          (insert-file-contents file)
  850.          ;; Save restriction in case file is already visited...
  851.          ;; Watch for those date stamps in history files!
  852.          (goto-char (point-max))
  853.          (while (and (< count comint-input-ring-size)
  854.                  (re-search-backward "^[ \t]*\\([^#\n].*\\)[ \t]*$"
  855.                          nil t))
  856.            (let ((history (buffer-substring (match-beginning 1)
  857.                             (match-end 1))))
  858.              (if (or (null comint-input-ignoredups)
  859.                  (ring-empty-p ring)
  860.                  (not (string-equal (ring-ref ring 0) history)))
  861.              (ring-insert-at-beginning ring history)))
  862.            (setq count (1+ count))))
  863.          (kill-buffer history-buf))
  864.        (setq comint-input-ring ring
  865.          comint-input-ring-index nil)))))
  866.  
  867. (defun comint-write-input-ring ()
  868.   "Writes the buffer's `comint-input-ring' to a history file.
  869. The name of the file is given by the variable `comint-input-ring-file-name'.
  870. The original contents of the file are lost if `comint-input-ring' is not empty.
  871. If `comint-input-ring-file-name' is nil this function does nothing.
  872.  
  873. Useful within process sentinels.
  874.  
  875. See also `comint-read-input-ring'."
  876.   (cond ((or (null comint-input-ring-file-name)
  877.          (equal comint-input-ring-file-name "")
  878.          (null comint-input-ring) (ring-empty-p comint-input-ring))
  879.      nil)
  880.     ((not (file-writable-p comint-input-ring-file-name))
  881.      (message "Cannot write history file %s" comint-input-ring-file-name))
  882.     (t
  883.      (let* ((history-buf (get-buffer-create " *Temp Input History*"))
  884.         (ring comint-input-ring)
  885.         (file comint-input-ring-file-name)
  886.         (index (ring-length ring)))
  887.        ;; Write it all out into a buffer first.  Much faster, but messier,
  888.        ;; than writing it one line at a time.
  889.        (save-excursion
  890.          (set-buffer history-buf)
  891.          (erase-buffer)
  892.          (while (> index 0)
  893.            (setq index (1- index))
  894.            (insert (ring-ref ring index) ?\n))
  895.          (write-region (buffer-string) nil file nil 'no-message)
  896.          (kill-buffer nil))))))
  897.  
  898. ;; XEmacs - FSF doesn't have this.
  899. (defun comint-restore-window-config (conf &optional message)
  900.   ;; Don't obscure buffer being edited
  901.   (or (eq (selected-window) (minibuffer-window))
  902.       (message "%s" (or message "Press space to flush")))
  903.   (sit-for 0)
  904.   (if (if (fboundp 'next-command-event)
  905.           ;; lemacs
  906.           (let ((ch (next-command-event)))
  907.             (if (eq (event-to-character ch) ?\ )
  908.                 t
  909.                 (progn (setq unread-command-event ch)
  910.                        nil)))
  911.           ;; v19 FSFmacs
  912.           (let ((ch (read-event)))
  913.             (if (eq ch ?\ )
  914.                 t
  915.                 (progn (setq unread-command-events (list ch))
  916.                        nil))))
  917.       (set-window-configuration conf)))
  918.  
  919.  
  920. (defun comint-dynamic-list-input-ring ()
  921.   "List in help buffer the buffer's input history."
  922.   (interactive)
  923.   (if (or (not (ringp comint-input-ring))
  924.       (ring-empty-p comint-input-ring))
  925.       (message "No history")
  926.     (let ((history nil)
  927.       (history-buffer " *Input History*")
  928.       (index (1- (ring-length comint-input-ring)))
  929.       (conf (current-window-configuration)))
  930.       ;; We have to build up a list ourselves from the ring vector.
  931.       (while (>= index 0)
  932.     (setq history (cons (ring-ref comint-input-ring index) history)
  933.           index (1- index)))
  934.       ;; Change "completion" to "history reference"
  935.       ;; to make the display accurate.
  936.       (with-output-to-temp-buffer history-buffer
  937.     (display-completion-list history)
  938.     (set-buffer history-buffer)
  939.     (forward-line 3)
  940.     (let ((buffer-read-only nil))
  941.       (while (search-backward "completion" nil 'move)
  942.         (replace-match "history reference"))))
  943.       (comint-restore-window-config conf))))
  944.  
  945. (defun comint-regexp-arg (prompt)
  946.   ;; Return list of regexp and prefix arg using PROMPT.
  947.   (let* ((minibuffer-history-sexp-flag nil)
  948.      ;; Don't clobber this.
  949.      (last-command last-command)
  950.      (regexp (read-from-minibuffer prompt nil nil nil
  951.                        'minibuffer-history-search-history)))
  952.     (list (if (string-equal regexp "")
  953.           (setcar minibuffer-history-search-history
  954.               (nth 1 minibuffer-history-search-history))
  955.         regexp)
  956.       (prefix-numeric-value current-prefix-arg))))
  957.  
  958. (defun comint-search-arg (arg)
  959.   ;; First make sure there is a ring and that we are after the process mark
  960.   (cond ((not (comint-after-pmark-p))
  961.      (error "Not at command line"))
  962.     ((or (null comint-input-ring)
  963.          (ring-empty-p comint-input-ring))
  964.      (error "Empty input ring"))
  965.     ((zerop arg)
  966.      ;; arg of zero resets search from beginning, and uses arg of 1
  967.      (setq comint-input-ring-index nil)
  968.      1)
  969.     (t
  970.      arg)))
  971.  
  972. (defun comint-search-start (arg)
  973.   ;; Index to start a directional search, starting at comint-input-ring-index
  974.   (if comint-input-ring-index
  975.       ;; If a search is running, offset by 1 in direction of arg
  976.       (mod (+ comint-input-ring-index (if (> arg 0) 1 -1))
  977.        (ring-length comint-input-ring))
  978.     ;; For a new search, start from beginning or end, as appropriate
  979.     (if (>= arg 0)
  980.     0                       ; First elt for forward search
  981.       (1- (ring-length comint-input-ring)))))  ; Last elt for backward search
  982.  
  983. (defun comint-previous-input-string (arg)
  984.   "Return the string ARG places along the input ring.
  985. Moves relative to `comint-input-ring-index'."
  986.   (ring-ref comint-input-ring (if comint-input-ring-index
  987.                   (mod (+ arg comint-input-ring-index)
  988.                        (ring-length comint-input-ring))
  989.                 arg)))
  990.  
  991. (defun comint-previous-input (arg)
  992.   "Cycle backwards through input history."
  993.   (interactive "*p")
  994.   (comint-previous-matching-input "." arg))
  995.  
  996. (defun comint-next-input (arg)
  997.   "Cycle forwards through input history."
  998.   (interactive "*p")
  999.   (comint-previous-input (- arg)))
  1000.  
  1001. (defun comint-previous-matching-input-string (regexp arg)
  1002.   "Return the string matching REGEXP ARG places along the input ring.
  1003. Moves relative to `comint-input-ring-index'."
  1004.   (let* ((pos (comint-previous-matching-input-string-position regexp arg)))
  1005.     (if pos (ring-ref comint-input-ring pos))))
  1006.  
  1007. (defun comint-previous-matching-input-string-position (regexp arg &optional start)
  1008.   "Return the index matching REGEXP ARG places along the input ring.
  1009. Moves relative to START, or `comint-input-ring-index'."
  1010.   (if (or (not (ringp comint-input-ring))
  1011.       (ring-empty-p comint-input-ring))
  1012.       (error "No history"))
  1013.   (let* ((len (ring-length comint-input-ring))
  1014.      (motion (if (> arg 0) 1 -1))
  1015.      (n (mod (- (or start (comint-search-start arg)) motion) len))
  1016.      (tried-each-ring-item nil)
  1017.      (prev nil))
  1018.     ;; Do the whole search as many times as the argument says.
  1019.     (while (and (/= arg 0) (not tried-each-ring-item))
  1020.       ;; Step once.
  1021.       (setq prev n
  1022.         n (mod (+ n motion) len))
  1023.       ;; If we haven't reached a match, step some more.
  1024.       (while (and (< n len) (not tried-each-ring-item)
  1025.           (not (string-match regexp (ring-ref comint-input-ring n))))
  1026.     (setq n (mod (+ n motion) len)
  1027.           ;; If we have gone all the way around in this search.
  1028.           tried-each-ring-item (= n prev)))
  1029.       (setq arg (if (> arg 0) (1- arg) (1+ arg))))
  1030.     ;; Now that we know which ring element to use, if we found it, return that.
  1031.     (if (string-match regexp (ring-ref comint-input-ring n))
  1032.     n)))
  1033.  
  1034. (defun comint-previous-matching-input (regexp arg)
  1035.   "Search backwards through input history for match for REGEXP.
  1036. \(Previous history elements are earlier commands.)
  1037. With prefix argument N, search for Nth previous match.
  1038. If N is negative, find the next or Nth next match."
  1039.   (interactive (comint-regexp-arg "Previous input matching (regexp): "))
  1040.   (setq arg (comint-search-arg arg))
  1041.   (let ((pos (comint-previous-matching-input-string-position regexp arg)))
  1042.     ;; Has a match been found?
  1043.     (if (null pos)
  1044.     (error "Not found")
  1045.       (setq comint-input-ring-index pos)
  1046.       (message "History item: %d" (1+ pos))
  1047.       (delete-region
  1048.        ;; Can't use kill-region as it sets this-command
  1049.        (process-mark (get-buffer-process (current-buffer))) (point))
  1050.       (insert (ring-ref comint-input-ring pos)))))
  1051.  
  1052. (defun comint-next-matching-input (regexp arg)
  1053.   "Search forwards through input history for match for REGEXP.
  1054. \(Later history elements are more recent commands.)
  1055. With prefix argument N, search for Nth following match.
  1056. If N is negative, find the previous or Nth previous match."
  1057.   (interactive (comint-regexp-arg "Next input matching (regexp): "))
  1058.   (comint-previous-matching-input regexp (- arg)))
  1059.  
  1060. (defun comint-previous-matching-input-from-input (arg)
  1061.   "Search backwards through input history for match for current input.
  1062. \(Previous history elements are earlier commands.)
  1063. With prefix argument N, search for Nth previous match.
  1064. If N is negative, search forwards for the -Nth following match."
  1065.   (interactive "p")
  1066.   (if (not (memq last-command '(comint-previous-matching-input-from-input
  1067.                 comint-next-matching-input-from-input)))
  1068.       ;; Starting a new search
  1069.       (setq comint-matching-input-from-input-string
  1070.         (buffer-substring
  1071.          (process-mark (get-buffer-process (current-buffer)))
  1072.          (point))
  1073.         comint-input-ring-index nil))
  1074.   (comint-previous-matching-input
  1075.    (concat "^" (regexp-quote comint-matching-input-from-input-string))
  1076.    arg))
  1077.  
  1078. (defun comint-next-matching-input-from-input (arg)
  1079.   "Search forwards through input history for match for current input.
  1080. \(Following history elements are more recent commands.)
  1081. With prefix argument N, search for Nth following match.
  1082. If N is negative, search backwards for the -Nth previous match."
  1083.   (interactive "p")
  1084.   (comint-previous-matching-input-from-input (- arg)))
  1085.  
  1086.  
  1087. (defun comint-replace-by-expanded-history (&optional silent)
  1088.   "Expand input command history references before point.
  1089. Expansion is dependent on the value of `comint-input-autoexpand'.
  1090.  
  1091. This function depends on the buffer's idea of the input history, which may not
  1092. match the command interpreter's idea, assuming it has one.
  1093.  
  1094. Assumes history syntax is like typical Un*x shells'.  However, since emacs
  1095. cannot know the interpreter's idea of input line numbers, assuming it has one,
  1096. it cannot expand absolute input line number references.
  1097.  
  1098. If the optional argument SILENT is non-nil, never complain
  1099. even if history reference seems erroneous.
  1100.  
  1101. See `comint-magic-space' and `comint-replace-by-expanded-history-before-point'.
  1102.  
  1103. Returns t if successful."
  1104.   (interactive)
  1105.   (if (and comint-input-autoexpand
  1106.        (string-match "!\\|^\\^" (funcall comint-get-old-input))
  1107.        (save-excursion (beginning-of-line)
  1108.                (looking-at comint-prompt-regexp)))
  1109.       ;; Looks like there might be history references in the command.
  1110.       (let ((previous-modified-tick (buffer-modified-tick)))
  1111.     (message "Expanding history references...")
  1112.     (comint-replace-by-expanded-history-before-point silent)
  1113.     (/= previous-modified-tick (buffer-modified-tick)))))
  1114.  
  1115.  
  1116. (defun comint-replace-by-expanded-history-before-point (silent)
  1117.   "Expand directory stack reference before point.
  1118. See `comint-replace-by-expanded-history'.  Returns t if successful."
  1119.   (save-excursion
  1120.     (let ((toend (- (save-excursion (end-of-line nil) (point)) (point)))
  1121.       (start (progn (comint-bol nil) (point))))
  1122.       ;; XEmacs - fsf has something weird and complex here that does the same thing.
  1123.       (while (re-search-forward
  1124.           "[!^]" (save-excursion (end-of-line nil) (- (point) toend)) t)
  1125.     ;; This seems a bit complex.  We look for references such as !!, !-num,
  1126.     ;; !foo, !?foo, !{bar}, !?{bar}, ^oh, ^my^, ^god^it, ^never^ends^.
  1127.     ;; If that wasn't enough, the plings can be suffixed with argument
  1128.     ;; range specifiers.
  1129.     ;; Argument ranges are complex too, so we hive off the input line,
  1130.     ;; referenced with plings, with the range string to `comint-args'.
  1131.     (setq comint-input-ring-index nil)
  1132.     (goto-char (match-beginning 0))    ; XEmacs
  1133.     (cond ((or (= (preceding-char) ?\\)
  1134.            (comint-within-quotes start (point)))
  1135.            ;; The history is quoted, or we're in quotes.
  1136.            (goto-char (match-end 0))) ; XEmacs
  1137.           ((looking-at "![0-9]+\\($\\|[^-]\\)")
  1138.            ;; We cannot know the interpreter's idea of input line numbers.
  1139.            (goto-char (match-end 0))
  1140.            (message "Absolute reference cannot be expanded"))
  1141.           ((looking-at "!-\\([0-9]+\\)\\(:?[0-9^$*-]+\\)?")
  1142.            ;; Just a number of args from `number' lines backward.
  1143.            (let ((number (1- (string-to-number
  1144.                   (buffer-substring (match-beginning 1)
  1145.                             (match-end 1))))))
  1146.          (if (<= number (ring-length comint-input-ring))
  1147.              (progn
  1148.                (replace-match
  1149.             (comint-args (comint-previous-input-string number)
  1150.                      (match-beginning 2) (match-end 2))
  1151.             t t)
  1152.                (setq comint-input-ring-index number)
  1153.                (message "History item: %d" (1+ number)))
  1154.            (goto-char (match-end 0))
  1155.            (message "Relative reference exceeds input history size"))))
  1156.           ((or (looking-at "!!?:?\\([0-9^$*-]+\\)") (looking-at "!!"))
  1157.            ;; Just a number of args from the previous input line.
  1158.            (replace-match
  1159.         (comint-args (comint-previous-input-string 0)
  1160.                  (match-beginning 1) (match-end 1)) t t)
  1161.            (message "History item: previous"))
  1162.           ((looking-at
  1163.         "!\\??\\({\\(.+\\)}\\|\\(\\sw+\\)\\)\\(:?[0-9^$*-]+\\)?")
  1164.            ;; Most recent input starting with or containing (possibly
  1165.            ;; protected) string, maybe just a number of args.  Phew.
  1166.            (let* ((mb1 (match-beginning 1)) (me1 (match-end 1))
  1167.               (mb2 (match-beginning 2)) (me2 (match-end 2))
  1168.               (exp (buffer-substring (or mb2 mb1) (or me2 me1)))
  1169.               (pref (if (save-match-data (looking-at "!\\?")) "" "^"))
  1170.               (pos (save-match-data
  1171.                  (comint-previous-matching-input-string-position
  1172.                   (concat pref (regexp-quote exp)) 1))))
  1173.          (if (null pos)
  1174.              (progn
  1175.                (goto-char (match-end 0))
  1176.                (or silent
  1177.                (progn (message "Not found")
  1178.                   (ding))))
  1179.            (setq comint-input-ring-index pos)
  1180.            (replace-match
  1181.             (comint-args (ring-ref comint-input-ring pos)
  1182.                  (match-beginning 4) (match-end 4))
  1183.             t t)
  1184.            (message "History item: %d" (1+ pos)))))
  1185.           ((looking-at "\\^\\([^^]+\\)\\^?\\([^^]*\\)\\^?")
  1186.            ;; Quick substitution on the previous input line.
  1187.            (let ((old (buffer-substring (match-beginning 1) (match-end 1)))
  1188.              (new (buffer-substring (match-beginning 2) (match-end 2)))
  1189.              (pos nil))
  1190.          (replace-match (comint-previous-input-string 0) t t)
  1191.          (setq pos (point))
  1192.          (goto-char (match-beginning 0))
  1193.          (if (not (search-forward old pos t))
  1194.              (or silent
  1195.              (error "Not found"))
  1196.            (replace-match new t t)
  1197.            (message "History item: substituted"))))
  1198.           (t
  1199.            (goto-char (match-end 0))))))))
  1200.  
  1201.  
  1202. (defun comint-magic-space (arg)
  1203.   "Expand input history references before point and insert ARG spaces.
  1204. A useful command to bind to SPC.  See `comint-replace-by-expanded-history'."
  1205.   (interactive "p")
  1206.   (comint-replace-by-expanded-history)
  1207.   (self-insert-command arg))
  1208.  
  1209. (defun comint-within-quotes (beg end)
  1210.   "Return t if the number of quotes between BEG and END is odd.
  1211. Quotes are single and double."
  1212.   (let ((countsq (comint-how-many-region "\\(^\\|[^\\\\]\\)\'" beg end))
  1213.     (countdq (comint-how-many-region "\\(^\\|[^\\\\]\\)\"" beg end)))
  1214.     (or (= (mod countsq 2) 1) (= (mod countdq 2) 1))))
  1215.  
  1216. (defun comint-how-many-region (regexp beg end)
  1217.   "Return number of matches for REGEXP from BEG to END."
  1218.   (let ((count 0))
  1219.     (save-excursion
  1220.       (save-match-data
  1221.     (goto-char beg)
  1222.     (while (re-search-forward regexp end t)
  1223.       (setq count (1+ count)))))
  1224.     count))
  1225.  
  1226. (defun comint-args (string begin end)
  1227.   ;; From STRING, return the args depending on the range specified in the text
  1228.   ;; from BEGIN to END.  If BEGIN is nil, assume all args.  Ignore leading `:'.
  1229.   ;; Range can be x-y, x-, -y, where x/y can be [0-9], *, ^, $.
  1230.   (save-match-data
  1231.     (if (null begin)
  1232.     (comint-arguments string 0 nil)
  1233.       (let* ((range (buffer-substring
  1234.              (if (eq (char-after begin) ?:) (1+ begin) begin) end))
  1235.          (nth (cond ((string-match "^[*^]" range) 1)
  1236.             ((string-match "^-" range) 0)
  1237.             ((string-equal range "$") nil)
  1238.             (t (string-to-number range))))
  1239.          (mth (cond ((string-match "[-*$]$" range) nil)
  1240.             ((string-match "-" range)
  1241.              (string-to-number (substring range (match-end 0))))
  1242.             (t nth))))
  1243.     (comint-arguments string nth mth)))))
  1244.  
  1245. ;; Return a list of arguments from ARG.  Break it up at the
  1246. ;; delimiters in comint-delimiter-argument-list.  Returned list is backwards.
  1247. (defun comint-delim-arg (arg)
  1248.   (if (null comint-delimiter-argument-list)
  1249.       (list arg)
  1250.     (let ((args nil)
  1251.       (pos 0)
  1252.       (len (length arg)))
  1253.       (while (< pos len)
  1254.     (let ((char (aref arg pos))
  1255.           (start pos))
  1256.       (if (memq char comint-delimiter-argument-list)
  1257.           (while (and (< pos len) (eq (aref arg pos) char))
  1258.         (setq pos (1+ pos)))
  1259.         (while (and (< pos len)
  1260.             (not (memq (aref arg pos)
  1261.                    comint-delimiter-argument-list)))
  1262.           (setq pos (1+ pos))))
  1263.       (setq args (cons (substring arg start pos) args))))
  1264.       args)))
  1265.  
  1266. (defun comint-arguments (string nth mth)
  1267.   "Return from STRING the NTH to MTH arguments.
  1268. NTH and/or MTH can be nil, which means the last argument.
  1269. Returned arguments are separated by single spaces.
  1270. We assume whitespace separates arguments, except within quotes.
  1271. Also, a run of one or more of a single character
  1272. in `comint-delimiter-argument-list' is a separate argument.
  1273. Argument 0 is the command name."
  1274.   (let ((argpart "[^ \n\t\"'`]+\\|\\(\"[^\"]*\"\\|'[^']*'\\|`[^`]*`\\)")
  1275.     (args ()) (pos 0)
  1276.     (count 0)
  1277.     beg str quotes)
  1278.     ;; Build a list of all the args until we have as many as we want.
  1279.     (while (and (or (null mth) (<= count mth))
  1280.         (string-match argpart string pos))
  1281.       (if (and beg (= pos (match-beginning 0)))
  1282.       ;; It's contiguous, part of the same arg.
  1283.       (setq pos (match-end 0)
  1284.         quotes (or quotes (match-beginning 1)))
  1285.     ;; It's a new separate arg.
  1286.     (if beg
  1287.         ;; Put the previous arg, if there was one, onto ARGS.
  1288.         (setq str (substring string beg pos)
  1289.           args (if quotes (cons str args)
  1290.              (nconc (comint-delim-arg str) args))
  1291.           count (1+ count)))
  1292.     (setq quotes (match-beginning 1))
  1293.     (setq beg (match-beginning 0))
  1294.     (setq pos (match-end 0))))
  1295.     (if beg
  1296.     (setq str (substring string beg pos)
  1297.           args (if quotes (cons str args)
  1298.              (nconc (comint-delim-arg str) args))
  1299.           count (1+ count)))
  1300.     (let ((n (or nth (1- count)))
  1301.       (m (if mth (1- (- count mth)) 0)))
  1302.       (mapconcat
  1303.        (function (lambda (a) a)) (nthcdr n (nreverse (nthcdr m args))) " "))))
  1304.  
  1305. ;;;
  1306. ;;; Input processing stuff
  1307. ;;;
  1308.  
  1309. (defun comint-send-input ()
  1310.   "Send input to process.
  1311. After the process output mark, sends all text from the process mark to
  1312. point as input to the process.  Before the process output mark, calls value
  1313. of variable `comint-get-old-input' to retrieve old input, copies it to the
  1314. process mark, and sends it.  If variable `comint-process-echoes' is nil,
  1315. a terminal newline is also inserted into the buffer and sent to the process
  1316. \(if it is non-nil, all text from the process mark to point is deleted,
  1317. since it is assumed the remote process will re-echo it).
  1318.  
  1319. Any history reference may be expanded depending on the value of the variable
  1320. `comint-input-autoexpand'.  The list of function names contained in the value
  1321. of `comint-input-filter-functions' is called on the input before sending it.
  1322. The input is entered into the input history ring, if the value of variable
  1323. `comint-input-filter' returns non-nil when called on the input.
  1324.  
  1325. If variable `comint-eol-on-send' is non-nil, then point is moved to the
  1326. end of line before sending the input.
  1327.  
  1328. If variable `comint-append-old-input' is non-nil, then the results of
  1329. calling `comint-get-old-input' are appended to the end of the buffer.
  1330. The new input will combine with any partially-typed text already present
  1331. after the process output mark.  Point is moved just before the newly
  1332. appended input, and a message is displayed prompting the user to type
  1333. \\[comint-send-input] again.
  1334.  
  1335. The values of `comint-get-old-input', `comint-input-filter-functions' and
  1336. `comint-input-filter' are chosen according to the command interpreter running
  1337. in the buffer.  E.g.,
  1338.  
  1339. If the interpreter is the csh,
  1340.     comint-get-old-input is the default: take the current line, discard any
  1341.         initial string matching regexp comint-prompt-regexp.
  1342.     comint-input-filter-functions monitors input for \"cd\", \"pushd\", and
  1343.         \"popd\" commands. When it sees one, it cd's the buffer.
  1344.     comint-input-filter is the default: returns t if the input isn't all white
  1345.     space.
  1346.  
  1347. If the comint is Lucid Common Lisp,
  1348.     comint-get-old-input snarfs the sexp ending at point.
  1349.     comint-input-filter-functions does nothing.
  1350.     comint-input-filter returns nil if the input matches input-filter-regexp,
  1351.         which matches (1) all whitespace (2) :a, :c, etc.
  1352.  
  1353. Similarly for Soar, Scheme, etc."
  1354.   (interactive)
  1355.   ;; Note that the input string does not include its terminal newline.
  1356.   (let ((proc (get-buffer-process (current-buffer))))
  1357.     (if (not proc) (error "Current buffer has no process")
  1358.       (let* ((pmark (process-mark proc))
  1359.          (pmark-val (marker-position pmark))
  1360.          ;; XEmacs - change by John Rose: confirm before sending input if
  1361.          ;; not after process mark.
  1362.          (append-here nil)
  1363.          (intxt (if (>= (point) pmark-val)
  1364.             (progn (if comint-eol-on-send (end-of-line))
  1365.                    (buffer-substring pmark (point)))
  1366.               (let ((copy (funcall comint-get-old-input)))
  1367.             (push-mark)
  1368.             (if (not comint-append-old-input)
  1369.                 (goto-char pmark-val)
  1370.               (setq append-here (point-max))
  1371.               (goto-char append-here))
  1372.             (insert copy)
  1373.             copy)))
  1374.          (input (if (not (eq comint-input-autoexpand 'input))
  1375.             ;; Just whatever's already there
  1376.             intxt
  1377.               ;; Expand and leave it visible in buffer
  1378.               (comint-replace-by-expanded-history t)
  1379.               (buffer-substring pmark (point))))
  1380.          (history (if (not (eq comint-input-autoexpand 'history))
  1381.               (if (eq comint-input-autoexpand nil)
  1382.                   ;; XEmacs - nil means leave it alone!
  1383.                   input
  1384.                 (comint-arguments input 0 nil))
  1385.             ;; This is messy 'cos ultimately the original
  1386.             ;; functions used do insertion, rather than return
  1387.             ;; strings.  We have to expand, then insert back.
  1388.             (comint-replace-by-expanded-history t)
  1389.             (let ((copy (buffer-substring pmark (point))))
  1390.               (delete-region pmark (point))
  1391.               (insert input)
  1392.               (comint-arguments copy 0 nil)))))
  1393.     (if append-here
  1394.         (progn
  1395.           (goto-char append-here)
  1396.           (message
  1397.            (substitute-command-keys
  1398.         "(\\[comint-send-input] to confirm)")))
  1399.       (if comint-process-echoes
  1400.           (delete-region pmark (point))
  1401.         (insert ?\n))
  1402.       (if (and (funcall comint-input-filter history)
  1403.            (or (null comint-input-ignoredups)
  1404.                (not (ringp comint-input-ring))
  1405.                (ring-empty-p comint-input-ring)
  1406.                (not (string-equal (ring-ref comint-input-ring 0)
  1407.                       history))))
  1408.           (ring-insert comint-input-ring history))
  1409.       ;; XEmacs - run the input filters on the history instead
  1410.       ;; of the input, so that the input sentinel is called on the
  1411.       ;; history-expanded text and sees "cd foo" instead of "cd !$".
  1412.       (run-hook-with-args 'comint-input-filter-functions
  1413.                   (concat history "\n"))
  1414.       (setq comint-input-ring-index nil)
  1415.       ;; Update the markers before we send the input
  1416.       ;; in case we get output amidst sending the input.
  1417.       (set-marker comint-last-input-start pmark)
  1418.       (set-marker comint-last-input-end (point))
  1419.       (set-marker (process-mark proc) (point))
  1420.       (comint-input-done)
  1421.       (funcall comint-input-sender proc input)
  1422.       (comint-input-setup)
  1423.       ;; XEmacs - A kludge to prevent the delay between insert and
  1424.       ;; process output affecting the display.  A case for a
  1425.       ;; comint-send-input-hook?
  1426.       (run-hook-with-args 'comint-output-filter-functions
  1427.                   (concat input "\n"))
  1428.       (comint-output-filter proc "")
  1429.       )))))
  1430. (defun comint-input-done ()
  1431.   "Finalized comint-input-extent so nothing more is added."
  1432.   (if (not comint-input-extent)
  1433.       (comint-input-setup))
  1434.   (set-extent-property comint-input-extent 'start-closed nil)
  1435.   (set-extent-property comint-input-extent 'end-closed nil)
  1436.   (set-extent-property comint-input-extent 'detachable t)
  1437.   )
  1438.  
  1439. (defun comint-input-setup ()
  1440.   "Insure the comint-input-extent is ready."
  1441.   (require 'comint-xemacs)
  1442.   (setq comint-input-extent (make-extent (point) (point-max)))
  1443.   (set-extent-property comint-input-extent 'detachable nil)
  1444.   (set-extent-property comint-input-extent 'start-closed t)
  1445.   (set-extent-property comint-input-extent 'end-closed t)
  1446.   (set-extent-face comint-input-extent 'comint-input-face)
  1447.   )
  1448.  
  1449. (defvar comint-input-extent nil
  1450.   "Current extent used for displaying text in buffer.");
  1451. (make-variable-buffer-local 'comint-input-extent)
  1452.  
  1453. ;; The purpose of using this filter for comint processes
  1454. ;; is to keep comint-last-input-end from moving forward
  1455. ;; when output is inserted.
  1456. (defun comint-output-filter (process string)
  1457.   ;; First check for killed buffer
  1458.   (let ((oprocbuf (process-buffer process)))
  1459.     (if (and oprocbuf (buffer-name oprocbuf))
  1460.     (let ((obuf (current-buffer))
  1461.           (opoint nil) (obeg nil) (oend nil))
  1462.       (set-buffer oprocbuf)
  1463.       (setq string (replace-in-string string "\^M" "")
  1464.         opoint (point)
  1465.         obeg (point-min)
  1466.         oend (point-max))
  1467.       ;; Keep stuff being output (before input) from using input-extent
  1468.       (if comint-input-extent
  1469.           (set-extent-property comint-input-extent 'start-closed nil))
  1470.       (let ((buffer-read-only nil)
  1471.         (nchars (length string))
  1472.         (ostart nil))
  1473.         (widen)
  1474.         (goto-char (process-mark process))
  1475.         (setq ostart (point))
  1476.         (if (<= (point) opoint)
  1477.         (setq opoint (+ opoint nchars)))
  1478.         ;; Insert after old_begv, but before old_zv.
  1479.         (if (< (point) obeg)
  1480.         (setq obeg (+ obeg nchars)))
  1481.         (if (<= (point) oend)
  1482.         (setq oend (+ oend nchars)))
  1483.         (insert-before-markers string)
  1484.         ;; Don't insert initial prompt outside the top of the window.
  1485.         (if (= (window-start (selected-window)) (point))
  1486.         (set-window-start (selected-window) (- (point) (length string))))
  1487.         (if (and comint-last-input-end
  1488.              (marker-buffer comint-last-input-end)
  1489.              (= (point) comint-last-input-end))
  1490.         (set-marker comint-last-input-end (- comint-last-input-end nchars)))
  1491.         (set-marker comint-last-output-start ostart)
  1492.         (set-marker (process-mark process) (point))
  1493.         (redraw-modeline))
  1494.       ;; Now insure everything inserted after (user input) is in extent
  1495.       (if (not comint-input-extent)
  1496.           (comint-input-setup))
  1497.       (set-extent-endpoints comint-input-extent (point) (point-max))
  1498.       (set-extent-property comint-input-extent 'start-closed t)
  1499.  
  1500.       (narrow-to-region obeg oend)
  1501.       (goto-char opoint)
  1502.       (run-hook-with-args 'comint-output-filter-functions string)
  1503.       (set-buffer obuf)))))
  1504.  
  1505. ;; XEmacs - Use a variable for this so that new commands can be added easily.
  1506. (defvar comint-scroll-to-bottom-on-input-commands
  1507.   '(self-insert-command
  1508.     mouse-yank
  1509.     mouse-yank-at-click
  1510.     x-insert-selection
  1511.     comint-previous-input
  1512.     comint-next-input
  1513.     comint-previous-matching-input
  1514.     comint-next-matching-input
  1515.     comint-previous-matching-input-from-input
  1516.     comint-next-matching-input-from-input
  1517.     )
  1518.   "List of functions which will cause the point to move to the end of comint buffers.")
  1519.  
  1520. (defun comint-preinput-scroll-to-bottom ()
  1521.   "Go to the end of buffer in all windows showing it.
  1522. Movement occurs if point in the selected window is not after the process mark,
  1523. and `this-command' is an insertion command.  Insertion commands recognised
  1524. are those in `comint-scroll-to-bottom-on-input-commands'.
  1525. Depends on the value of `comint-scroll-to-bottom-on-input'.
  1526.  
  1527. This function should be a pre-command hook."
  1528.   (if (and comint-scroll-to-bottom-on-input
  1529.        (memq this-command comint-scroll-to-bottom-on-input-commands))
  1530.       (let* ((selected (selected-window))
  1531.          (current (current-buffer))
  1532.          (process (get-buffer-process current))
  1533.          (scroll comint-scroll-to-bottom-on-input))
  1534.     (if (and process (< (point) (process-mark process))
  1535.          scroll (not (window-minibuffer-p selected)))
  1536.         (if (eq scroll 'this)
  1537.         (goto-char (point-max))
  1538.           (walk-windows
  1539.            (function (lambda (window)
  1540.                (if (and (eq (window-buffer window) current)
  1541.                     (or (eq scroll t) (eq scroll 'all)))
  1542.                    ;; XEmacs - fsf does this the hard way.
  1543.                    (set-window-point window (point-max))
  1544.                  )))
  1545.            'not-minibuf t))))))
  1546.  
  1547. (defun comint-postoutput-scroll-to-bottom (string)
  1548.   "Go to the end of buffer in all windows showing it.
  1549. Does not scroll if the current line is the last line in the buffer.
  1550. Depends on the value of `comint-scroll-to-bottom-on-output' and
  1551. `comint-scroll-show-maximum-output'.
  1552.  
  1553. This function should be in the list `comint-output-filter-functions'."
  1554.   (let* ((selected (selected-window))
  1555.      (current (current-buffer))
  1556.      (process (get-buffer-process current))
  1557.      (scroll comint-scroll-to-bottom-on-output))
  1558.     ;; XEmacs - don't select windows as they're walked.
  1559.     (if process
  1560.     (walk-windows
  1561.       (function (lambda (window)
  1562.             (if (eq (window-buffer window) current)
  1563.            (progn
  1564.          (if (and (< (window-point window)
  1565.                  (process-mark process))
  1566.                           (or (eq scroll t) (eq scroll 'all)
  1567.                               ;; Maybe user wants point to jump to the end.
  1568.                               (and (eq scroll 'this)
  1569.                                    (eq selected window))
  1570.                               (and (eq scroll 'others)
  1571.                                    (not (eq selected window)))
  1572.                               ;; If point was at the end, keep it at the end.
  1573.                               (>= (window-point window)
  1574.                                   (- (process-mark process) (length string)))))
  1575.              (set-window-point window (process-mark process)))
  1576.          ;; Optionally scroll so that the text
  1577.          ;; ends at the bottom of the window.
  1578.          (if (and comint-scroll-show-maximum-output
  1579.               (>= (window-point window)
  1580.                   (process-mark process))
  1581.                           ;; XEmacs - lemacs addition
  1582.                           (not (pos-visible-in-window-p (point-max) window)))
  1583.              (save-excursion
  1584.                (set-window-point window (point-max))
  1585.                (recenter
  1586.             ;; XEmacs - lemacs addition
  1587.                          (cond ((integerp comint-scroll-show-maximum-output)
  1588.                                 comint-scroll-show-maximum-output)
  1589.                                ((floatp comint-scroll-show-maximum-output)
  1590.                                 (floor (* (window-height window)
  1591.                                           comint-scroll-show-maximum-output)
  1592.                                        1))
  1593.                                (t
  1594.                                 -1))
  1595.              )
  1596.                (sit-for 0)))
  1597.          ))))
  1598.      nil t))))
  1599.  
  1600. (defun comint-truncate-buffer (&optional string)
  1601.   "Truncate the buffer to `comint-buffer-maximum-size'.
  1602. This function could be on `comint-output-filter-functions' or bound to a key."
  1603.   (interactive)
  1604.   (save-excursion
  1605.     (goto-char (point-max))
  1606.     (forward-line (- comint-buffer-maximum-size))
  1607.     (beginning-of-line)
  1608.     (delete-region (point-min) (point))))
  1609.  
  1610. (defun comint-strip-ctrl-m (&optional string)
  1611.   "Strip trailing `^M' characters from the current output group.
  1612. This function could be on `comint-output-filter-functions' or bound to a key."
  1613.   (interactive)
  1614.   (let ((pmark (process-mark (get-buffer-process (current-buffer)))))
  1615.     (save-excursion
  1616.       (goto-char
  1617.        (if (interactive-p) comint-last-input-end comint-last-output-start))
  1618.       (while (re-search-forward "\r+$" pmark t)
  1619.     (replace-match "" t t)))))
  1620. (defalias 'shell-strip-ctrl-m 'comint-strip-ctrl-m)
  1621.  
  1622. (defun comint-show-maximum-output ()
  1623.   "Put the end of the buffer at the bottom of the window."
  1624.   (interactive)
  1625.   (goto-char (point-max))
  1626.   (recenter -1))
  1627.  
  1628. (defun comint-get-old-input-default ()
  1629.   "Default for `comint-get-old-input'.
  1630. Take the current line, and discard any initial text matching
  1631. `comint-prompt-regexp'."
  1632.   (save-excursion
  1633.     (beginning-of-line)
  1634.     (comint-skip-prompt)
  1635.     (let ((beg (point)))
  1636.       (end-of-line)
  1637.       (buffer-substring beg (point)))))
  1638.  
  1639. (defun comint-copy-old-input ()
  1640.   "Insert after prompt old input at point as new input to be edited.
  1641. Calls `comint-get-old-input' to get old input."
  1642.   (interactive)
  1643.   (let ((input (funcall comint-get-old-input))
  1644.      (process (get-buffer-process (current-buffer))))
  1645.     (if (not process)
  1646.     (error "Current buffer has no process")
  1647.       (goto-char (process-mark process))
  1648.       (insert input))))
  1649.  
  1650. (defun comint-skip-prompt ()
  1651.   "Skip past the text matching regexp `comint-prompt-regexp'.
  1652. If this takes us past the end of the current line, don't skip at all."
  1653.   (let ((eol (save-excursion (end-of-line) (point)))
  1654.     ;; XEmacs - Arbitrary limit:  prompt can be up to 10 lines long.
  1655.     (search-limit (save-excursion (forward-line -10) (point))))
  1656.     (if (and (save-excursion
  1657.            (goto-char eol)
  1658.            (re-search-backward comint-prompt-regexp search-limit t))
  1659.          (<= (match-beginning 0) (point))
  1660.          (> (match-end 0) (point))
  1661.          (<= (match-end 0) eol))
  1662.     (goto-char (match-end 0)))))
  1663.  
  1664. (defun comint-after-pmark-p ()
  1665.   "Return t if point is after the process output marker."
  1666.   (let ((pmark (process-mark (get-buffer-process (current-buffer)))))
  1667.     (<= (marker-position pmark) (point))))
  1668.  
  1669. (defun comint-simple-send (proc string)
  1670.   "Default function for sending to PROC input STRING.
  1671. This just sends STRING plus a newline. To override this,
  1672. set the hook `comint-input-sender'."
  1673.   (comint-send-string proc string)
  1674.   (comint-send-string proc "\n"))
  1675.  
  1676. ;; XEmacs - fsf doesn't bind this to ^A, but we do.  There is some merit to
  1677. ;; their change, so we change the behavior of the function to act the same
  1678. ;; as normal ^A unless we're after the process mark.  For the old behavior,
  1679. ;; use ^C^A as in FSF. --Stig
  1680. (defun comint-bol (arg)
  1681.   "Goes to the beginning of line, then skips past the prompt, if any.
  1682. If prefix argument is given (\\[universal-argument]) the prompt is not skipped.
  1683.  
  1684. The prompt skip is done by skipping text matching the regular expression
  1685. `comint-prompt-regexp', a buffer local variable."
  1686.   (interactive "_P")
  1687.   (let ((skip (and (null arg)
  1688.            (or (not (eq (lookup-key global-map (this-command-keys))
  1689.                 'beginning-of-line))
  1690.                ;; If the buffer's process has gone bye-bye
  1691.                ;; revert to being just beginning-of-line.
  1692.                (not (get-buffer-process (current-buffer)))
  1693.                (comint-after-pmark-p)))))
  1694.     (beginning-of-line)
  1695.     (if skip (comint-skip-prompt))))
  1696.  
  1697. ;; XEmacs - more like an xterm interaction model...
  1698. (defun comint-universal-argument ()
  1699.   "Erase the current line of input, or begin a numeric argument.
  1700.  
  1701. In buffers with interactive subprocesses, this modified version of
  1702. `universal-argument' erases the current line of user input just as ^U erases a
  1703. line of text at the UNIX command prompt.
  1704.  
  1705. Otherwise, begin a numeric argument for the following command.
  1706. Digits or minus sign following \\[universal-argument] make up the numeric argument.
  1707. \\[universal-argument] following the digits or minus sign ends the argument.
  1708. \\[universal-argument] without digits or minus sign provides 4 as argument.
  1709. Repeating \\[universal-argument] without digits or minus sign
  1710.  multiplies the argument by 4 each time."
  1711.   (interactive)
  1712.   (let ((proc (get-buffer-process (current-buffer))))
  1713.     (if (and proc (> (point) (process-mark proc)))
  1714.     (progn (comint-bol nil)
  1715.            (kill-region (point) (save-excursion (end-of-line) (point))))
  1716.       (let (key)
  1717.     (setq key (read-key-sequence nil t))
  1718.     (while (equal (key-binding key) 'universal-argument)
  1719.       (setq key (read-key-sequence nil t)))))))
  1720.  
  1721. ;;; These three functions are for entering text you don't want echoed or
  1722. ;;; saved -- typically passwords to ftp, telnet, or somesuch.
  1723. ;;; Just enter m-x send-invisible and type in your line, or add
  1724. ;;; `comint-watch-for-password-prompt' to `comint-output-filter-functions'.
  1725.  
  1726. ;; XEmacs has a standard function for this.
  1727. (defun comint-read-noecho (prompt &optional stars)
  1728.   "Read a password from the user.
  1729. See documentation of `read-passwd' for more info."
  1730.   (read-passwd prompt))
  1731.  
  1732. (defun send-invisible (str)
  1733.   "Read a string without echoing.
  1734. Then send it to the process running in the current buffer.  A new-line
  1735. is additionally sent.  String is not saved on comint input history list.
  1736. Security bug: your string can still be temporarily recovered with
  1737. \\[view-lossage]."
  1738.   (interactive "P") ; Defeat snooping via C-x esc
  1739.   (let ((proc (get-buffer-process (current-buffer))))
  1740.     (if (not proc)
  1741.     (error "Current buffer has no process")
  1742.       (comint-send-string
  1743.        proc (if (stringp str) str (comint-read-noecho "Non-echoed text: " t)))
  1744.       (comint-send-string proc "\n"))))
  1745.  
  1746. (defun comint-watch-for-password-prompt (string)
  1747.   "Prompt in the minibuffer for password and send without echoing.
  1748. This function uses `send-invisible' to read and send a password to the buffer's
  1749. process if STRING contains a password prompt defined by
  1750. `comint-password-prompt-regexp'.
  1751.  
  1752. This function could be in the list `comint-output-filter-functions'."
  1753.   (if (string-match comint-password-prompt-regexp string)
  1754.       (send-invisible nil)))
  1755.  
  1756. ;;; Low-level process communication
  1757.  
  1758. (defalias 'comint-send-string 'process-send-string)
  1759. (defalias 'comint-send-region 'process-send-region)
  1760.  
  1761. ;;; Random input hackage
  1762.  
  1763. (defun comint-kill-output ()
  1764.   "Kill all output from interpreter since last input.
  1765. Does not delete the prompt."
  1766.   (interactive)
  1767.   (let ((proc (get-buffer-process (current-buffer)))
  1768.     (replacement nil))
  1769.     (save-excursion
  1770.       (let ((pmark (progn (goto-char (process-mark proc))
  1771.               (beginning-of-line nil)
  1772.               (point-marker))))
  1773.     ;; XEmacs - kill in case we want it back...
  1774.     (kill-region comint-last-input-end pmark)
  1775.     (goto-char (process-mark proc))
  1776.     (setq replacement (concat "*** output flushed ***\n"
  1777.                   (buffer-substring pmark (point))))
  1778.     (delete-region pmark (point))))
  1779.     ;; Output message and put back prompt
  1780.     (comint-output-filter proc replacement)))
  1781.  
  1782. ;; XEmacs - don't move cursor unless necessary...
  1783. (defun comint-show-output ()
  1784.   "Display start of this batch of interpreter output at top of window.
  1785. Also put cursor there if the current position is not visible.
  1786. If the cursor is moved, then a mark is set at its old location."
  1787.   (interactive)
  1788.   (let ((pos (point)))
  1789.     (goto-char (or (marker-position comint-last-input-end) (point-max)))
  1790.     (beginning-of-line 0)
  1791.     (set-window-start (selected-window) (point))
  1792.     (if (pos-visible-in-window-p pos)
  1793.     (goto-char pos)
  1794.       (save-excursion
  1795.     (goto-char pos)
  1796.     (push-mark))
  1797.       (comint-skip-prompt))))
  1798.  
  1799. (defun comint-interrupt-subjob ()
  1800.   "Interrupt the current subjob."
  1801.   (interactive)
  1802.   (interrupt-process nil comint-ptyp))
  1803.  
  1804. (defun comint-kill-subjob ()
  1805.   "Send kill signal to the current subjob."
  1806.   (interactive)
  1807.   (kill-process nil comint-ptyp))
  1808.  
  1809. (defun comint-quit-subjob ()
  1810.   "Send quit signal to the current subjob."
  1811.   (interactive)
  1812.   (quit-process nil comint-ptyp))
  1813.  
  1814. (defun comint-stop-subjob ()
  1815.   "Stop the current subjob.
  1816. WARNING: if there is no current subjob, you can end up suspending
  1817. the top-level process running in the buffer. If you accidentally do
  1818. this, use \\[comint-continue-subjob] to resume the process. (This
  1819. is not a problem with most shells, since they ignore this signal.)"
  1820.   (interactive)
  1821.   (stop-process nil comint-ptyp))
  1822.  
  1823. (defun comint-continue-subjob ()
  1824.   "Send CONT signal to process buffer's process group.
  1825. Useful if you accidentally suspend the top-level process."
  1826.   (interactive)
  1827.   (continue-process nil comint-ptyp))
  1828.  
  1829. (defun comint-kill-input ()
  1830.   "Kill all text from last stuff output by interpreter to point."
  1831.   (interactive)
  1832.   (let ((pmark (process-mark (get-buffer-process (current-buffer)))))
  1833.     (if (> (point) (marker-position pmark))
  1834.     (kill-region pmark (point)))))
  1835.  
  1836. (defun comint-delchar-or-maybe-eof (arg)
  1837.   "Delete ARG characters forward, or (if at eob) send an EOF to subprocess."
  1838.   (interactive "p")
  1839.   (if (eobp)
  1840.       (process-send-eof)
  1841.     (delete-char arg)))
  1842.  
  1843. (defun comint-send-eof ()
  1844.   "Send an EOF to the current buffer's process."
  1845.   (interactive)
  1846.   (process-send-eof))
  1847.  
  1848.  
  1849. (defun comint-backward-matching-input (regexp arg)
  1850.   "Search backward through buffer for match for REGEXP.
  1851. Matches are searched for on lines that match `comint-prompt-regexp'.
  1852. With prefix argument N, search for Nth previous match.
  1853. If N is negative, find the next or Nth next match."
  1854.   (interactive (comint-regexp-arg "Backward input matching (regexp): "))
  1855.   (let* ((re (concat comint-prompt-regexp ".*" regexp))
  1856.      (pos (save-excursion (end-of-line (if (> arg 0) 0 1))
  1857.                   (if (re-search-backward re nil t arg)
  1858.                   (point)))))
  1859.     (if (null pos)
  1860.     (progn (message "Not found")
  1861.            (ding))
  1862.       (goto-char pos)
  1863.       (comint-bol nil))))
  1864.  
  1865. (defun comint-forward-matching-input (regexp arg)
  1866.   "Search forward through buffer for match for REGEXP.
  1867. Matches are searched for on lines that match `comint-prompt-regexp'.
  1868. With prefix argument N, search for Nth following match.
  1869. If N is negative, find the previous or Nth previous match."
  1870.   (interactive (comint-regexp-arg "Forward input matching (regexp): "))
  1871.   (comint-backward-matching-input regexp (- arg)))
  1872.  
  1873.  
  1874. (defun comint-next-prompt (n)
  1875.   "Move to end of Nth next prompt in the buffer.
  1876. See `comint-prompt-regexp'."
  1877.   (interactive "_p")            ; XEmacs - zmacs-regions
  1878.   (let ((paragraph-start comint-prompt-regexp))
  1879.     (end-of-line (if (> n 0) 1 0))
  1880.     (forward-paragraph n)
  1881.     (comint-skip-prompt)))
  1882.  
  1883. (defun comint-previous-prompt (n)
  1884.   "Move to end of Nth previous prompt in the buffer.
  1885. See `comint-prompt-regexp'."
  1886.   (interactive "_p")            ; XEmacs
  1887.   (comint-next-prompt (- n)))
  1888.  
  1889. ;;; Support for source-file processing commands.
  1890. ;;;============================================================================
  1891. ;;; Many command-interpreters (e.g., Lisp, Scheme, Soar) have
  1892. ;;; commands that process files of source text (e.g. loading or compiling
  1893. ;;; files). So the corresponding process-in-a-buffer modes have commands
  1894. ;;; for doing this (e.g., lisp-load-file). The functions below are useful
  1895. ;;; for defining these commands.
  1896. ;;;
  1897. ;;; Alas, these guys don't do exactly the right thing for Lisp, Scheme
  1898. ;;; and Soar, in that they don't know anything about file extensions.
  1899. ;;; So the compile/load interface gets the wrong default occasionally.
  1900. ;;; The load-file/compile-file default mechanism could be smarter -- it
  1901. ;;; doesn't know about the relationship between filename extensions and
  1902. ;;; whether the file is source or executable. If you compile foo.lisp
  1903. ;;; with compile-file, then the next load-file should use foo.bin for
  1904. ;;; the default, not foo.lisp. This is tricky to do right, particularly
  1905. ;;; because the extension for executable files varies so much (.o, .bin,
  1906. ;;; .lbin, .mo, .vo, .ao, ...).
  1907.  
  1908.  
  1909. ;;; COMINT-SOURCE-DEFAULT -- determines defaults for source-file processing
  1910. ;;; commands.
  1911. ;;;
  1912. ;;; COMINT-CHECK-SOURCE -- if FNAME is in a modified buffer, asks you if you
  1913. ;;; want to save the buffer before issuing any process requests to the command
  1914. ;;; interpreter.
  1915. ;;;
  1916. ;;; COMINT-GET-SOURCE -- used by the source-file processing commands to prompt
  1917. ;;; for the file to process.
  1918.  
  1919. ;;; (COMINT-SOURCE-DEFAULT previous-dir/file source-modes)
  1920. ;;;============================================================================
  1921. ;;; This function computes the defaults for the load-file and compile-file
  1922. ;;; commands for tea, soar, cmulisp, and cmuscheme modes.
  1923. ;;;
  1924. ;;; - PREVIOUS-DIR/FILE is a pair (directory . filename) from the last
  1925. ;;; source-file processing command. NIL if there hasn't been one yet.
  1926. ;;; - SOURCE-MODES is a list used to determine what buffers contain source
  1927. ;;; files: if the major mode of the buffer is in SOURCE-MODES, it's source.
  1928. ;;; Typically, (lisp-mode) or (scheme-mode).
  1929. ;;;
  1930. ;;; If the command is given while the cursor is inside a string, *and*
  1931. ;;; the string is an existing filename, *and* the filename is not a directory,
  1932. ;;; then the string is taken as default. This allows you to just position
  1933. ;;; your cursor over a string that's a filename and have it taken as default.
  1934. ;;;
  1935. ;;; If the command is given in a file buffer whose major mode is in
  1936. ;;; SOURCE-MODES, then the filename is the default file, and the
  1937. ;;; file's directory is the default directory.
  1938. ;;;
  1939. ;;; If the buffer isn't a source file buffer (e.g., it's the process buffer),
  1940. ;;; then the default directory & file are what was used in the last source-file
  1941. ;;; processing command (i.e., PREVIOUS-DIR/FILE).  If this is the first time
  1942. ;;; the command has been run (PREVIOUS-DIR/FILE is nil), the default directory
  1943. ;;; is the cwd, with no default file. (\"no default file\" = nil)
  1944. ;;;
  1945. ;;; SOURCE-REGEXP is typically going to be something like (tea-mode)
  1946. ;;; for T programs, (lisp-mode) for Lisp programs, (soar-mode lisp-mode)
  1947. ;;; for Soar programs, etc.
  1948. ;;;
  1949. ;;; The function returns a pair: (default-directory . default-file).
  1950.  
  1951. (defun comint-source-default (previous-dir/file source-modes)
  1952.   (cond ((and buffer-file-name (memq major-mode source-modes))
  1953.      (cons (file-name-directory    buffer-file-name)
  1954.            (file-name-nondirectory buffer-file-name)))
  1955.     (previous-dir/file)
  1956.     (t
  1957.      (cons default-directory nil))))
  1958.  
  1959.  
  1960. ;;; (COMINT-CHECK-SOURCE fname)
  1961. ;;;============================================================================
  1962. ;;; Prior to loading or compiling (or otherwise processing) a file (in the CMU
  1963. ;;; process-in-a-buffer modes), this function can be called on the filename.
  1964. ;;; If the file is loaded into a buffer, and the buffer is modified, the user
  1965. ;;; is queried to see if he wants to save the buffer before proceeding with
  1966. ;;; the load or compile.
  1967.  
  1968. (defun comint-check-source (fname)
  1969.   (let ((buff (get-file-buffer fname)))
  1970.     (if (and buff
  1971.          (buffer-modified-p buff)
  1972.          (y-or-n-p (format "Save buffer %s first? " (buffer-name buff))))
  1973.     ;; save BUFF.
  1974.     (let ((old-buffer (current-buffer)))
  1975.       (set-buffer buff)
  1976.       (save-buffer)
  1977.       (set-buffer old-buffer)))))
  1978.  
  1979.  
  1980. ;;; (COMINT-GET-SOURCE prompt prev-dir/file source-modes mustmatch-p)
  1981. ;;;============================================================================
  1982. ;;; COMINT-GET-SOURCE is used to prompt for filenames in command-interpreter
  1983. ;;; commands that process source files (like loading or compiling a file).
  1984. ;;; It prompts for the filename, provides a default, if there is one,
  1985. ;;; and returns the result filename.
  1986. ;;;
  1987. ;;; See COMINT-SOURCE-DEFAULT for more on determining defaults.
  1988. ;;;
  1989. ;;; PROMPT is the prompt string. PREV-DIR/FILE is the (directory . file) pair
  1990. ;;; from the last source processing command.  SOURCE-MODES is a list of major
  1991. ;;; modes used to determine what file buffers contain source files.  (These
  1992. ;;; two arguments are used for determining defaults). If MUSTMATCH-P is true,
  1993. ;;; then the filename reader will only accept a file that exists.
  1994. ;;;
  1995. ;;; A typical use:
  1996. ;;; (interactive (comint-get-source "Compile file: " prev-lisp-dir/file
  1997. ;;;                                 '(lisp-mode) t))
  1998.  
  1999. ;;; This is pretty stupid about strings. It decides we're in a string
  2000. ;;; if there's a quote on both sides of point on the current line.
  2001. (defun comint-extract-string ()
  2002.   "Return string around POINT that starts the current line, or nil."
  2003.   (save-excursion
  2004.     (let* ((point (point))
  2005.        (bol (progn (beginning-of-line) (point)))
  2006.        (eol (progn (end-of-line) (point)))
  2007.        (start (progn (goto-char point)
  2008.              (and (search-backward "\"" bol t)
  2009.                   (1+ (point)))))
  2010.        (end (progn (goto-char point)
  2011.                (and (search-forward "\"" eol t)
  2012.                 (1- (point))))))
  2013.       (and start end
  2014.        (buffer-substring start end)))))
  2015.  
  2016. (defun comint-get-source (prompt prev-dir/file source-modes mustmatch-p)
  2017.   (let* ((def (comint-source-default prev-dir/file source-modes))
  2018.          (stringfile (comint-extract-string))
  2019.      (sfile-p (and stringfile
  2020.                (condition-case ()
  2021.                (file-exists-p stringfile)
  2022.              (error nil))
  2023.                (not (file-directory-p stringfile))))
  2024.      (defdir  (if sfile-p (file-name-directory stringfile)
  2025.                       (car def)))
  2026.      (deffile (if sfile-p (file-name-nondirectory stringfile)
  2027.                       (cdr def)))
  2028.      (ans (read-file-name (if deffile (format "%s(default %s) "
  2029.                           prompt    deffile)
  2030.                   prompt)
  2031.                   defdir
  2032.                   (concat defdir deffile)
  2033.                   mustmatch-p)))
  2034.     (list (expand-file-name (substitute-in-file-name ans)))))
  2035.  
  2036. ;;; I am somewhat divided on this string-default feature. It seems
  2037. ;;; to violate the principle-of-least-astonishment, in that it makes
  2038. ;;; the default harder to predict, so you actually have to look and see
  2039. ;;; what the default really is before choosing it. This can trip you up.
  2040. ;;; On the other hand, it can be useful, I guess. I would appreciate feedback
  2041. ;;; on this.
  2042. ;;;     -Olin
  2043.  
  2044.  
  2045. ;;; Simple process query facility.
  2046. ;;; ===========================================================================
  2047. ;;; This function is for commands that want to send a query to the process
  2048. ;;; and show the response to the user. For example, a command to get the
  2049. ;;; arglist for a Common Lisp function might send a "(arglist 'foo)" query
  2050. ;;; to an inferior Common Lisp process.
  2051. ;;;
  2052. ;;; This simple facility just sends strings to the inferior process and pops
  2053. ;;; up a window for the process buffer so you can see what the process
  2054. ;;; responds with.  We don't do anything fancy like try to intercept what the
  2055. ;;; process responds with and put it in a pop-up window or on the message
  2056. ;;; line. We just display the buffer. Low tech. Simple. Works good.
  2057.  
  2058. ;;; Send to the inferior process PROC the string STR. Pop-up but do not select
  2059. ;;; a window for the inferior process so that its response can be seen.
  2060. (defun comint-proc-query (proc str)
  2061.   (let* ((proc-buf (process-buffer proc))
  2062.      (proc-mark (process-mark proc)))
  2063.     (display-buffer proc-buf)
  2064.     (set-buffer proc-buf) ; but it's not the selected *window*
  2065.     (let ((proc-win (get-buffer-window proc-buf))
  2066.       (proc-pt (marker-position proc-mark)))
  2067.       (comint-send-string proc str) ; send the query
  2068.       (accept-process-output proc)  ; wait for some output
  2069.       ;; Try to position the proc window so you can see the answer.
  2070.       ;; This is bogus code. If you delete the (sit-for 0), it breaks.
  2071.       ;; I don't know why. Wizards invited to improve it.
  2072.       (if (not (pos-visible-in-window-p proc-pt proc-win))
  2073.       (let ((opoint (window-point proc-win)))
  2074.         (set-window-point proc-win proc-mark)
  2075.         (sit-for 0)
  2076.         (if (not (pos-visible-in-window-p opoint proc-win))
  2077.         (push-mark opoint)
  2078.           (set-window-point proc-win opoint)))))))
  2079.  
  2080.  
  2081. ;;; Filename/command/history completion in a buffer
  2082. ;;; ===========================================================================
  2083. ;;; Useful completion functions, courtesy of the Ergo group.
  2084.  
  2085. ;;; Six commands:
  2086. ;;; comint-dynamic-complete        Complete or expand command, filename,
  2087. ;;;                                     history at point.
  2088. ;;; comint-dynamic-complete-filename    Complete filename at point.
  2089. ;;; comint-dynamic-list-filename-completions List completions in help buffer.
  2090. ;;; comint-replace-by-expanded-filename    Expand and complete filename at point;
  2091. ;;;                    replace with expanded/completed name.
  2092. ;;; comint-dynamic-simple-complete    Complete stub given candidates.
  2093.  
  2094. ;;; These are not installed in the comint-mode keymap. But they are
  2095. ;;; available for people who want them. Shell-mode installs them:
  2096. ;;; (define-key shell-mode-map "\t" 'comint-dynamic-complete)
  2097. ;;; (define-key shell-mode-map "\M-?"
  2098. ;;;             'comint-dynamic-list-filename-completions)))
  2099. ;;;
  2100. ;;; Commands like this are fine things to put in load hooks if you
  2101. ;;; want them present in specific modes.
  2102.  
  2103. (defcustom comint-completion-autolist nil
  2104.   "*If non-nil, automatically list possibilities on partial completion.
  2105. This mirrors the optional behavior of tcsh."
  2106.   :type 'boolean
  2107.   :group 'comint-completion)
  2108.  
  2109. (defcustom comint-completion-addsuffix t
  2110.   "*If non-nil, add a `/' to completed directories, ` ' to file names.
  2111. If a cons pair, it should be of the form (DIRSUFFIX . FILESUFFIX) where
  2112. DIRSUFFIX and FILESUFFIX are strings added on unambiguous or exact completion.
  2113. This mirrors the optional behavior of tcsh."
  2114.   :type 'boolean
  2115.   :group 'comint-completion)
  2116.  
  2117. (defcustom comint-completion-recexact nil
  2118.   "*If non-nil, use shortest completion if characters cannot be added.
  2119. This mirrors the optional behavior of tcsh.
  2120.  
  2121. A non-nil value is useful if `comint-completion-autolist' is non-nil too."
  2122.   :type 'boolean
  2123.   :group 'comint-completion)
  2124.  
  2125. (defcustom comint-completion-fignore nil
  2126.   "*List of suffixes to be disregarded during file completion.
  2127. This mirrors the optional behavior of bash and tcsh.
  2128.  
  2129. Note that this applies to `comint-dynamic-complete-filename' only."
  2130.   :type '(repeat (string :tag "Suffix"))
  2131.   :group 'comint-completion)
  2132.  
  2133. (defvar comint-file-name-prefix ""
  2134.   "Prefix prepended to absolute file names taken from process input.
  2135. This is used by comint's and shell's completion functions, and by shell's
  2136. directory tracking functions.")
  2137.  
  2138. (defvar comint-file-name-quote-list nil
  2139.   "List of characters to quote with `\' when in a file name.
  2140.  
  2141. This is a good thing to set in mode hooks.")
  2142.  
  2143.  
  2144. (defun comint-directory (directory)
  2145.   ;; Return expanded DIRECTORY, with `comint-file-name-prefix' if absolute.
  2146.   (expand-file-name (if (file-name-absolute-p directory)
  2147.             (concat comint-file-name-prefix directory)
  2148.               directory)))
  2149.  
  2150.  
  2151. (defun comint-word (word-chars)
  2152.   "Return the word of WORD-CHARS at point, or nil if non is found.
  2153. Word constituents are considered to be those in WORD-CHARS, which is like the
  2154. inside of a \"[...]\" (see `skip-chars-forward')."
  2155.   (save-excursion
  2156.     (let ((non-word-chars (concat "[^\\\\" word-chars "]")) (here (point)))
  2157.       (while (and (re-search-backward non-word-chars nil 'move)
  2158.           ;(memq (char-after (point)) shell-file-name-quote-list)
  2159.           (eq (preceding-char) ?\\))
  2160.     (backward-char 1))
  2161.       ;; Don't go forward over a word-char (this can happen if we're at bob).
  2162.       (if (or (not (bobp)) (looking-at non-word-chars))
  2163.       (forward-char 1))
  2164.       ;; Set match-data to match the entire string.
  2165.       (if (< (point) here)
  2166.       (progn (store-match-data (list (point) here))
  2167.          (match-string 0))))))
  2168.  
  2169. (defun comint-extract-current-pathname ()
  2170.   "Return the file name at point.
  2171. `@' or `.' are not valid characters at the end of the filename."
  2172.   (save-excursion
  2173.     (re-search-forward "@?\\([^-A-Za-z0-9_,/+%.~]\\|$\\)")
  2174.     (goto-char (match-beginning 0))
  2175.     (re-search-backward
  2176.      "[^-A-Za-z0-9_,/+%.@~][-A-Za-z0-9_,/+%.@~]+[-A-Za-z0-9_+%~]"
  2177.      nil t)
  2178.     (buffer-substring (1+ (match-beginning 0)) (match-end 0))))
  2179.  
  2180. (defun comint-match-partial-filename ()
  2181.   "Return the filename at point, or nil if none is found.
  2182. Environment variables are substituted.  See `comint-word'."
  2183.   (let ((filename (comint-word "~/A-Za-z0-9+@:_.$#%,={}-")))
  2184.     (and filename (substitute-in-file-name (comint-unquote-filename filename)))))
  2185.  
  2186.  
  2187. (defun comint-quote-filename (filename)
  2188.   "Return FILENAME with magic characters quoted.
  2189. Magic characters are those in `comint-file-name-quote-list'."
  2190.   (if (null comint-file-name-quote-list)
  2191.       filename
  2192.     (let ((regexp
  2193.        (format "\\(^\\|[^\\]\\)\\([%s]\\)"
  2194.         (mapconcat 'char-to-string comint-file-name-quote-list ""))))
  2195.       (save-match-data
  2196.     (while (string-match regexp filename)
  2197.       (setq filename (replace-match "\\1\\\\\\2" nil nil filename)))
  2198.     filename))))
  2199.  
  2200. (defun comint-unquote-filename (filename)
  2201.   "Return FILENAME with quoted characters unquoted."
  2202.   (if (null comint-file-name-quote-list)
  2203.       filename
  2204.     (save-match-data
  2205.       (while (string-match "\\\\\\(.\\)" filename)
  2206.     (setq filename (replace-match "\\1" nil nil filename)))
  2207.       filename)))
  2208.  
  2209.  
  2210. ;;;###autoload
  2211. (defun comint-dynamic-complete ()
  2212.   "Dynamically perform completion at point.
  2213. Calls the functions in `comint-dynamic-complete-functions' to perform
  2214. completion until a function returns non-nil, at which point completion is
  2215. assumed to have occurred."
  2216.   (interactive)
  2217.   (run-hook-with-args-until-success 'comint-dynamic-complete-functions))
  2218.  
  2219.  
  2220. (defun comint-dynamic-complete-filename ()
  2221.   "Dynamically complete the filename at point.
  2222. Completes if after a filename.  See `comint-match-partial-filename' and
  2223. `comint-dynamic-complete-as-filename'.
  2224. This function is similar to `comint-replace-by-expanded-filename', except that
  2225. it won't change parts of the filename already entered in the buffer; it just
  2226. adds completion characters to the end of the filename.  A completions listing
  2227. may be shown in a help buffer if completion is ambiguous.
  2228.  
  2229. Completion is dependent on the value of `comint-completion-addsuffix',
  2230. `comint-completion-recexact' and `comint-completion-fignore', and the timing of
  2231. completions listing is dependent on the value of `comint-completion-autolist'.
  2232.  
  2233. Returns t if successful."
  2234.   (interactive)
  2235.   (if (comint-match-partial-filename)
  2236.       (prog2 (or (window-minibuffer-p (selected-window))
  2237.          (message "Completing file name..."))
  2238.       (comint-dynamic-complete-as-filename))))
  2239.  
  2240.  
  2241. (defun comint-dynamic-complete-as-filename ()
  2242.   "Dynamically complete at point as a filename.
  2243. See `comint-dynamic-complete-filename'.  Returns t if successful."
  2244.   (let* ((completion-ignore-case nil)
  2245.      (completion-ignored-extensions comint-completion-fignore)
  2246.      (file-name-handler-alist nil)
  2247.      (minibuffer-p (window-minibuffer-p (selected-window)))
  2248.      (success t)
  2249.      (dirsuffix (cond ((not comint-completion-addsuffix) "")
  2250.               ((not (consp comint-completion-addsuffix)) "/")
  2251.               (t (car comint-completion-addsuffix))))
  2252.      (filesuffix (cond ((not comint-completion-addsuffix) "")
  2253.                ((not (consp comint-completion-addsuffix)) " ")
  2254.                (t (cdr comint-completion-addsuffix))))
  2255.      (filename (or (comint-match-partial-filename) ""))
  2256.      (pathdir (file-name-directory filename))
  2257.      (pathnondir (file-name-nondirectory filename))
  2258.      (directory (if pathdir (comint-directory pathdir) default-directory))
  2259.      (completion (file-name-completion pathnondir directory)))
  2260.     (cond ((null completion)
  2261.            (if minibuffer-p (ding) (message "No completions of %s" filename))
  2262.            (setq success nil))
  2263.           ((eq completion t)            ; Means already completed "file".
  2264.            (insert filesuffix)
  2265.            (or minibuffer-p (message "Sole completion")))
  2266.           ((string-equal completion "") ; Means completion on "directory/".
  2267.            (comint-dynamic-list-filename-completions))
  2268.           (t                            ; Completion string returned.
  2269.            (let ((file (concat (file-name-as-directory directory) completion)))
  2270.          (insert (comint-quote-filename
  2271.               (substring (directory-file-name completion)
  2272.                  (length pathnondir))))
  2273.              (cond ((symbolp (file-name-completion completion directory))
  2274.                     ;; We inserted a unique completion.
  2275.             (insert (if (file-directory-p file) dirsuffix filesuffix))
  2276.                     (or minibuffer-p (message "Completed")))
  2277.                    ((and comint-completion-recexact comint-completion-addsuffix
  2278.                          (string-equal pathnondir completion)
  2279.                          (file-exists-p file))
  2280.                     ;; It's not unique, but user wants shortest match.
  2281.                     (insert (if (file-directory-p file) dirsuffix filesuffix))
  2282.                     (or minibuffer-p (message "Completed shortest")))
  2283.                    ((or comint-completion-autolist
  2284.                         (string-equal pathnondir completion))
  2285.                     ;; It's not unique, list possible completions.
  2286.                     (comint-dynamic-list-filename-completions))
  2287.                    (t
  2288.                     (or minibuffer-p (message "Partially completed")))))))
  2289.     success))
  2290.  
  2291.  
  2292. (defun comint-replace-by-expanded-filename ()
  2293.   "Dynamically expand and complete the filename at point.
  2294. Replace the filename with an expanded, canonicalised and completed replacement.
  2295. \"Expanded\" means environment variables (e.g., $HOME) and `~'s are replaced
  2296. with the corresponding directories.  \"Canonicalised\" means `..'  and `.' are
  2297. removed, and the filename is made absolute instead of relative.  For expansion
  2298. see `expand-file-name' and `substitute-in-file-name'.  For completion see
  2299. `comint-dynamic-complete-filename'."
  2300.   (interactive)
  2301.   (replace-match (expand-file-name (comint-match-partial-filename)) t t)
  2302.   (comint-dynamic-complete-filename))
  2303.  
  2304.  
  2305. (defun comint-dynamic-simple-complete (stub candidates)
  2306.   "Dynamically complete STUB from CANDIDATES list.
  2307. This function inserts completion characters at point by completing STUB from
  2308. the strings in CANDIDATES.  A completions listing may be shown in a help buffer
  2309. if completion is ambiguous.
  2310.  
  2311. Returns nil if no completion was inserted.
  2312. Returns `sole' if completed with the only completion match.
  2313. Returns `shortest' if completed with the shortest of the completion matches.
  2314. Returns `partial' if completed as far as possible with the completion matches.
  2315. Returns `listed' if a completion listing was shown.
  2316.  
  2317. See also `comint-dynamic-complete-filename'."
  2318.   (let* ((completion-ignore-case nil)
  2319.      (suffix (cond ((not comint-completion-addsuffix) "")
  2320.                ((not (consp comint-completion-addsuffix)) " ")
  2321.                (t (cdr comint-completion-addsuffix))))
  2322.      (candidates (mapcar (function (lambda (x) (list x))) candidates))
  2323.      (completions (all-completions stub candidates)))
  2324.     (cond ((null completions)
  2325.         (message "No completions of %s" stub)
  2326.        nil)
  2327.        ((= 1 (length completions))    ; Gotcha!
  2328.         (let ((completion (car completions)))
  2329.           (if (string-equal completion stub)
  2330.           (message "Sole completion")
  2331.             (insert (substring completion (length stub)))
  2332.             (message "Completed"))
  2333.          (insert suffix)
  2334.          'sole))
  2335.        (t                ; There's no unique completion.
  2336.         (let ((completion (try-completion stub candidates)))
  2337.           ;; Insert the longest substring.
  2338.           (insert (substring completion (length stub)))
  2339.           (cond ((and comint-completion-recexact comint-completion-addsuffix
  2340.               (string-equal stub completion)
  2341.               (member completion completions))
  2342.              ;; It's not unique, but user wants shortest match.
  2343.              (insert suffix)
  2344.              (message "Completed shortest")
  2345.             'shortest)
  2346.             ((or comint-completion-autolist
  2347.              (string-equal stub completion))
  2348.              ;; It's not unique, list possible completions.
  2349.              (comint-dynamic-list-completions completions)
  2350.             'listed)
  2351.             (t
  2352.             (message "Partially completed")
  2353.             'partial)))))))
  2354.  
  2355.  
  2356. (defun comint-dynamic-list-filename-completions ()
  2357.   "List in help buffer possible completions of the filename at point."
  2358.   (interactive)
  2359.   (let* ((completion-ignore-case nil)
  2360.      (file-name-handler-alist nil)
  2361.      (filename (or (comint-match-partial-filename) ""))
  2362.      (pathdir (file-name-directory filename))
  2363.      (pathnondir (file-name-nondirectory filename))
  2364.      (directory (if pathdir (comint-directory pathdir) default-directory))
  2365.      (completions (file-name-all-completions pathnondir directory)))
  2366.     (if (not completions)
  2367.     (message "No completions of %s" filename)
  2368.       (comint-dynamic-list-completions
  2369.        (mapcar 'comint-quote-filename completions)))))
  2370.  
  2371.  
  2372. ;;;###autoload
  2373. (defun comint-dynamic-list-completions (completions)
  2374.   "List in help buffer sorted COMPLETIONS.
  2375. Typing SPC flushes the help buffer."
  2376.   (let ((conf (current-window-configuration)))
  2377.     (with-output-to-temp-buffer "*Completions*"
  2378.       (display-completion-list (sort completions 'string-lessp)))
  2379.     ;; XEmacs - centralize this
  2380.     (comint-restore-window-config conf)))
  2381.  
  2382. ;; #### - FSFmacs doesn't have this and I'm not gonna nuke it just yet, but
  2383. ;; it seems awfully redundant to have this here when compile.el does pretty
  2384. ;; much the same thing.  --Stig
  2385.  
  2386. ;;; Filename and source location extraction from a buffer.
  2387. ;;; lemacs change by John Rose
  2388. ;;; ===========================================================================
  2389. ;;; Functions for recognizing and extracting file names and line numbers.
  2390. ;;; C-c C-f attempts to extract a location from the current line, and
  2391. ;;; go to that location.
  2392.  
  2393. ;;; One command:
  2394. ;;; comint-find-source-code        Extract source location and follow it.
  2395.  
  2396. ;;; This should be installed globally, since file names and source locations
  2397. ;;; are ubiquitous.  However, don't overwrite an existing key binding.
  2398. (if (not (lookup-key global-map "\C-c\C-f"))
  2399.     (global-set-key "\C-c\C-f" 'comint-find-source-code))
  2400.  
  2401. ;;; Utility functions:
  2402. ;;; comint-extract-source-location    Parse source loc. from buffer or string.
  2403. ;;; comint-extract-current-pathname    Extract potential pathname around point.
  2404. ;;; comint-match-partial-pathname    Match a potential pathname before point.
  2405.  
  2406. (defconst comint-source-location-patterns
  2407.   '(;; grep (and cpp): file.c: 10:
  2408.     ("\\(^\\|[ \t]\\)\\([^ \t\n]+\\): *\\([0-9]+\\):[ \t]*\\(.*\\)" (grep cpp) (2 3 4))
  2409.     ;; cpp: #line 10 "file.c"
  2410.     ("#\\(line\\)? *\\([0-9]+\\) *\"\\([^\"\n]+\\)\"" cpp (3 2))
  2411.     ;; cc: "file.c", line 10
  2412.     ("\"\\([^\"\n]+\\)\", line +\\([0-9]+\\)\\(:[ \t]+\\(.*\\)\\)?" cc (1 2 4))
  2413.     ;; f77: line 10 of file.c
  2414.     ("line +\\([0-9]+\\) +of +\\([^ \t\n]+\\)\\(:[ \t]+\\(.*\\)\\)?" f77 (2 1 4))
  2415.     ;; perl: ...at file.c line 10.
  2416.     ;; perl: ...at file.c line 10, near "foo"
  2417.     ("^\\(.*\\) at \\([^ \t\n]+\\) line +\\([0-9]+\\)\\(\\.$\\|, \\)"
  2418.      perl (2 3 1))
  2419.     ;; dbx: line 10 in "file.c"
  2420.     ("\\(^\\(.*\\)[ \t]+at \\)?line +\\([0-9]+\\) +[in of file]+ +\"\\([^\"\n]+\\)\""
  2421.      dbx (4 3 2))
  2422.     ;; dbx: "file.c":10
  2423.     ("\"\\([^\"\n]+\\)\":\\([0-9]+\\)" dbx (1 2))
  2424.     ;; centerline: "file.c:10"
  2425.     ("\"\\([^\"\n]+\\):\\([0-9]+\\)\"" centerline (1 2))
  2426.     ;; lint: : file.c(10)
  2427.     (": *\\([^ \t\n)]+\\) *(\\([0-9]+\\))" lint (1 2))
  2428.     ;; lint: file.c(10) :
  2429.     ("\\(^\\|[ \t]\\)\\([^ \t\n)]+\\) *(\\([0-9]+\\)) *:" lint (2 3))
  2430.     ;; lint: ( file.c(10) )
  2431.     ("( +\\([^ \t\n)]+\\) *(\\([0-9]+\\)) +)" lint (1 2))
  2432.     ;; troff: `file.c', line 10
  2433.     ("[\"`']\\([^\"`'\n]+\\)[\"`'], line +\\([0-9]+\\)" troff (1 2))
  2434.     ;; ri: "file.c" 10:
  2435.     ("\"\\([^\"\n]+\\)\" *\\([0-9]+\\):" ri (1 2)) ;;Never heard of ri.
  2436.     ;; mod: File file.c, line 10
  2437.     ("[Ff]ile +\\([^ \t\n]+\\), line +\\([0-9]+\\)" mod (1 2))
  2438.     ;; ksh: file.c[10] :
  2439.     ("\\(^\\|[ \t]\\)\\([^ \t\n)]+\\) *\\[\\([0-9]+\\)\\] *:[ \t]+\\(.*\\)"
  2440.      ksh (2 3 4))
  2441.     ;; shell: file.c: syntax error at line 10
  2442.     ("\\(^\\|[ \t]\\)\\([^ \t\n:]+\\):[ \t]+\\(.*\\)[ \t]+[, at]*line +\\([0-9]+\\)"
  2443.      sh (2 4 3) -1)
  2444.     )
  2445.   "Series of regexps matching file number locations.
  2446. Each list entry is a 3-list of a regexp, a program name, and up to 3 numbers.
  2447. The numbers name regexp fields which will hold the file, line number,
  2448. and associated diagnostic message (if any).
  2449. The program name is a symbol or list of symbols, and
  2450. is returned unexamined from `comint-extract-source-location';
  2451. it should be a guess at who produced the message, e.g., 'cc'.
  2452.  
  2453. In the case of multiple matches, `comint-extract-source-location'
  2454. will return the leftmost, longest match of the highest priority.
  2455. The priority of most patterns is 0, but a fourth element on
  2456. the list, if present, specifies a different priority.
  2457.  
  2458. The regexps initially stored here are based on the one in compile.el
  2459. \(although the pattern containing 'of' must also contain 'line').
  2460. They are also drawn from the Unix filters 'error' and 'fwarn'.
  2461. The patterns are known to recognize errors from the following
  2462. Un*x language processors:
  2463.   cpp, cc, dbx, lex, f77, Centerline C, sh (Bourne), lint, mod
  2464. The following language processors do not incorporate file names
  2465. in every error message, and so are more difficult to accomodate:
  2466.   yacc, pc, csh
  2467.    ")
  2468.  
  2469. (defun comint-extract-source-location (&optional start end commands markers)
  2470.   "Return a 6-list of (file line command diagnostic mstart mend),
  2471. obtained by parsing the current buffer between START and END,
  2472. which default to the bounds of the current line.
  2473.  
  2474. Use the list comint-source-location-patterns to guide parsing.
  2475.  
  2476. The match returned will be on the latest line containing a match, but
  2477. will be the earliest possible match on that line.
  2478.  
  2479. START can also be a string, in which case it inserted in the buffer
  2480. \"*Extract File and Line*\" and parsed there.
  2481.  
  2482. COMMANDS is an optional list of pattern types, which has the effect of
  2483. temporarily reducing the list comint-source-location-patterns
  2484. to only those entries which apply to the given commands.
  2485.  
  2486. Return NIL if there is no recognizable source location.
  2487.  
  2488. MSTART and MEND give the limits of the matched source location.
  2489.  
  2490. If MARKERS is true, return no strings, but rather cons cells
  2491. of the form (beg-marker . end-marker).
  2492. "
  2493.   (if (not start)
  2494.       (progn
  2495.     (setq start (save-excursion (beginning-of-line) (point)))
  2496.     (setq end (save-excursion (end-of-line) (point)))))
  2497.   (if (stringp start)
  2498.       (save-excursion
  2499.     (set-buffer (get-buffer-create "*Extract File and Line*"))
  2500.     (erase-buffer)
  2501.     (insert start)
  2502.     (comint-extract-source-location (point-min) (point-max) commands markers))
  2503.     (let ((ptr (if (and (consp commands)
  2504.             (consp (car commands)))
  2505.            (prog1 commands (setq commands nil))
  2506.          comint-source-location-patterns))
  2507.       pat
  2508.       (found-bol (- (point-min) 1))
  2509.       (found-prio -999999)
  2510.       found-beg
  2511.       found-end
  2512.       found-pat
  2513.       found-data
  2514.       set-found-data)
  2515.       (setq set-found-data
  2516.         (function (lambda (data)
  2517.             (while found-data
  2518.               (let ((m (car found-data)))
  2519.                 (if (markerp m) (set-marker m nil)))
  2520.               (setq found-data (cdr found-data)))
  2521.             (setq found-data data))))
  2522.       (if (and commands (not (listp commands)))
  2523.       (setq commands (list commands)))
  2524.       (save-excursion
  2525.     (save-restriction
  2526.       (narrow-to-region start end)
  2527.       (while ptr
  2528.         (setq pat (car ptr) ptr (cdr ptr))
  2529.         (goto-char (point-max))
  2530.         (if (and (or (null commands)
  2531.              (if (consp (nth 1 pat))
  2532.                  (member (nth 1 pat) commands)
  2533.                ;; If (cadr pat) is a list, each list element
  2534.                ;; is a command that might produce this.
  2535.                (let ((ptr (nth 1 pat))
  2536.                  (ismem nil))
  2537.                  (while (and ptr (not ismem))
  2538.                    (if (member (car ptr) commands)
  2539.                    (setq ismem t))
  2540.                    (setq ptr (cdr ptr)))
  2541.                  ismem)))
  2542.              (re-search-backward (nth 0 pat) found-bol t))
  2543.         (let (beg end bol prio)
  2544.           (setq beg (match-beginning 0))
  2545.           (setq end (match-end 0))
  2546.           (beginning-of-line)
  2547.           (setq bol (point))
  2548.           (re-search-forward (nth 0 pat))
  2549.           (if (> (match-beginning 0) beg)
  2550.               (error "comint-extract-source-location botch"))
  2551.           (setq beg (match-beginning 0))
  2552.           (setq end (match-end 0))
  2553.           (setq prio (or (nth 3 pat) 0))
  2554.           (if (or (> bol found-bol)
  2555.               (and (= bol found-bol)
  2556.                    (or (> prio found-prio)
  2557.                    (and (= prio found-prio)
  2558.                     (or (< beg found-beg)
  2559.                         (and (= beg found-beg)
  2560.                          (> end found-end)))))))
  2561.               (progn
  2562.             (setq found-bol bol)
  2563.             (setq found-prio prio)
  2564.             (setq found-beg beg)
  2565.             (setq found-end end)
  2566.             (setq found-pat pat)
  2567.             (funcall set-found-data (match-data)))))))))
  2568.       (and found-data
  2569.        (let* ((command (nth 1 found-pat))
  2570.           (fields (nth 2 found-pat))
  2571.           (f1 (nth 0 fields))
  2572.           (f2 (nth 1 fields))
  2573.           (f3 (nth 2 fields))
  2574.           (get-field
  2575.            (function
  2576.             (lambda (fn)
  2577.               (and fn
  2578.                (let ((beg (match-beginning fn))
  2579.                  (end (match-end fn)))
  2580.                  (and beg end (> end beg)
  2581.                   (if markers
  2582.                       (cons (copy-marker beg) (copy-marker end))
  2583.                     (buffer-substring beg end)))))))))
  2584.          (store-match-data found-data)
  2585.          (funcall set-found-data nil)
  2586.          (let ((file (funcall get-field f1))
  2587.            (line (funcall get-field f2))
  2588.            (diagnostic (funcall get-field f3))
  2589.            (mstart (match-beginning 0))
  2590.            (mend (match-end 0)))
  2591.            ;; (carefully use all match-data before calling string-match)
  2592.            (list
  2593.         file
  2594.         (if (and (stringp line)
  2595.              (prog1
  2596.                  (string-match "\\`[0-9]+\\'" line)
  2597.                (store-match-data found-data)))
  2598.             (string-to-int line)
  2599.           line)
  2600.         command
  2601.         diagnostic
  2602.         mstart
  2603.         mend
  2604.         ))))
  2605.       )))
  2606.  
  2607. ;;; Commands for extracting source locations:
  2608.  
  2609. (defcustom comint-find-source-code-max-lines 100
  2610.   "*Maximum number of lines to search backward for a source location,
  2611. when using \\[comint-find-source-code\\] with an interactive prefix."
  2612.   :type 'integer
  2613.   :group 'comint-source)
  2614.  
  2615. (defcustom comint-find-source-file-hook nil
  2616.   "*Function to call instead of comint-default-find-source-file
  2617. when comint-find-source-code parses out a file name and then wants to
  2618. visit its buffer.  The sole argument is the file name.  The function
  2619. must find the file, setting the current buffer, and return the file
  2620. name.  It may also adjust the file name.  If you change this variable,
  2621. make it buffer local."
  2622.   :type 'function
  2623.   :group 'comint-source)
  2624.  
  2625. (defcustom comint-goto-source-line-hook nil
  2626.   "*Function to call instead of comint-default-goto-source-line
  2627. after comint-find-source-code finds a file and then wants to
  2628. go to a line number mentioned in a source location.
  2629. The sole argument is the line number.  The function must
  2630. return the line number, possibly adjusted.  If you change
  2631. this variable, make it buffer local."
  2632.   :type 'function
  2633.   :group 'comint-source)
  2634.  
  2635. (defun comint-find-source-code (multi-line)
  2636.   "Search backward from point for a source location.
  2637. If a source location is found in the current line,
  2638. go to that location.
  2639.  
  2640. If MULTI-LINE is false (this is the interactive prefix flag),
  2641. then only look for source locations in the current line.
  2642. Otherwise, look within comint-find-source-code-max-lines
  2643. before point.  If a source location is found on a previous line, move
  2644. point to that location, so that another use of \\[comint-find-source-code\\]
  2645. will go to the indicated place.
  2646.  
  2647. If no source location is found, then try to extract a filename
  2648. around the point, using comint-extract-current-pathname.
  2649.  
  2650. In any case, if the file does not exist, prompt the user for
  2651. a pathname that does.  Sometimes the file's directory needs
  2652. hand adjustment.
  2653.  
  2654. This command uses comint-extract-source-location, which is customizable.
  2655. Also, once a source file and line have been extracted, it uses
  2656. comint-find-source-file-hook and comint-goto-source-line-hook
  2657. to interpret them."
  2658.   (interactive "P")
  2659.   (let* ((beg (save-excursion
  2660.         (if multi-line
  2661.             (forward-line (min 0 (- comint-find-source-code-max-lines)))
  2662.           (beginning-of-line))
  2663.         (point)))
  2664.      (end (save-excursion (end-of-line) (point)))
  2665.      (res (or (comint-extract-source-location beg end)
  2666.           (let ((file (comint-extract-current-pathname)))
  2667.             (and file
  2668.              (list file nil nil nil
  2669.                    (match-beginning 0)
  2670.                    (match-end 0))))
  2671.           (error "Not sitting on a source location."))))
  2672.     (let ((file (nth 0 res))
  2673.       (line (nth 1 res))
  2674.       ;;(cmd (nth 2 res))
  2675.       (info (nth 3 res))
  2676.       (mbeg (nth 4 res))
  2677.       (mend (nth 5 res))
  2678.       dofind)
  2679.       (setq dofind
  2680.         (not (and multi-line
  2681.               mend
  2682.               (< mend (save-excursion (beginning-of-line) (point))))))
  2683.       (if (not dofind)
  2684.       (goto-char mbeg)
  2685.     (progn
  2686.       (setq file
  2687.         (funcall (or comint-find-source-file-hook
  2688.                  'comint-default-find-source-file)
  2689.              file))
  2690.       (if line
  2691.           (setq line
  2692.             (funcall (or comint-goto-source-line-hook
  2693.                  'comint-default-goto-source-line)
  2694.                  line)))
  2695.       ))
  2696.       (message "%s%s of %s%s%s"
  2697.            (if dofind
  2698.            "" (substitute-command-keys
  2699.                "Hit \\[comint-find-source-code] for "))
  2700.            (cond ((null line) "current line")
  2701.              ((numberp line) (format "line %s" line))
  2702.              (t line))
  2703.            (file-name-nondirectory file)
  2704.            (if info ": " "") (or info "")))))
  2705.  
  2706.  
  2707. (defun comint-default-find-source-file (file)
  2708.   "Action taken by \\[comint-find-source-code] when find-source-file-hook is nil.
  2709. It calls substitute-in-file-name.  If the file does not exist, it prompts
  2710. for the right pathname, using a similar pathname derived from a nearby
  2711. buffer as a default.  It then calls find-file-other-window and returns the
  2712. amended file name."
  2713.   (setq file (substitute-in-file-name file))
  2714.   (if (not (file-readable-p file))
  2715.       (setq file (comint-fixup-source-file-name file)))
  2716.   (find-file-other-window file)
  2717.   file)
  2718.  
  2719. (defun comint-fixup-source-file-name (file)
  2720.   (let (dir ptr nondir bfile res)
  2721.     (setq nondir (file-name-nondirectory file))
  2722.     (setq ptr (buffer-list))
  2723.     (while (and ptr (not dir))
  2724.       (setq bfile (buffer-file-name (car ptr)))
  2725.       (if (and bfile (equal (file-name-nondirectory bfile) nondir))
  2726.       (setq dir (file-name-directory bfile)
  2727.         file (file-name-nondirectory bfile)))
  2728.       (setq ptr (cdr ptr)))
  2729.     (setq res
  2730.       (read-file-name "Source file: " dir t nil file))
  2731.     (if (eq res t)
  2732.     (expand-file-name file dir)
  2733.       res)))
  2734.  
  2735. (defun comint-default-goto-source-line (line)
  2736.   "Action taken by \\[comint-find-source-code] when goto-source-line-hook is nil.
  2737. It widens & pushes the mark, then does goto-line in the current buffer.
  2738. It returns its line argument."
  2739.   (widen)
  2740.   (setq line (max line 0))
  2741.   (setq line (min line (+ 1 (count-lines (point-min) (point-max)))))
  2742.   (push-mark)
  2743.   (goto-line line)
  2744.   line)
  2745.  
  2746. ;;; Converting process modes to use comint mode
  2747. ;;; ===========================================================================
  2748. ;;; The code in the Emacs 19 distribution has all been modified to use comint
  2749. ;;; where needed.  However, there are `third-party' packages out there that
  2750. ;;; still use the old shell mode.  Here's a guide to conversion.
  2751. ;;;
  2752. ;;; Renaming variables
  2753. ;;; Most of the work is renaming variables and functions. These are the common
  2754. ;;; ones:
  2755. ;;; Local variables:
  2756. ;;;    last-input-start    comint-last-input-start
  2757. ;;;     last-input-end        comint-last-input-end
  2758. ;;;    shell-prompt-pattern    comint-prompt-regexp
  2759. ;;;     shell-set-directory-error-hook <no equivalent>
  2760. ;;; Miscellaneous:
  2761. ;;;    shell-set-directory    <unnecessary>
  2762. ;;;     shell-mode-map        comint-mode-map
  2763. ;;; Commands:
  2764. ;;;    shell-send-input    comint-send-input
  2765. ;;;    shell-send-eof        comint-delchar-or-maybe-eof
  2766. ;;;     kill-shell-input    comint-kill-input
  2767. ;;;    interrupt-shell-subjob    comint-interrupt-subjob
  2768. ;;;    stop-shell-subjob    comint-stop-subjob
  2769. ;;;    quit-shell-subjob    comint-quit-subjob
  2770. ;;;    kill-shell-subjob    comint-kill-subjob
  2771. ;;;    kill-output-from-shell    comint-kill-output
  2772. ;;;    show-output-from-shell    comint-show-output
  2773. ;;;    copy-last-shell-input    Use comint-previous-input/comint-next-input
  2774. ;;;
  2775. ;;; SHELL-SET-DIRECTORY is gone, its functionality taken over by
  2776. ;;; SHELL-DIRECTORY-TRACKER, the shell mode's comint-input-filter-functions.
  2777. ;;; Comint mode does not provide functionality equivalent to
  2778. ;;; shell-set-directory-error-hook; it is gone.
  2779. ;;;
  2780. ;;; comint-last-input-start is provided for modes which want to munge
  2781. ;;; the buffer after input is sent, perhaps because the inferior
  2782. ;;; insists on echoing the input.  The LAST-INPUT-START variable in
  2783. ;;; the old shell package was used to implement a history mechanism,
  2784. ;;; but you should think twice before using comint-last-input-start
  2785. ;;; for this; the input history ring often does the job better.
  2786. ;;;
  2787. ;;; If you are implementing some process-in-a-buffer mode, called foo-mode, do
  2788. ;;; *not* create the comint-mode local variables in your foo-mode function.
  2789. ;;; This is not modular.  Instead, call comint-mode, and let *it* create the
  2790. ;;; necessary comint-specific local variables. Then create the
  2791. ;;; foo-mode-specific local variables in foo-mode.  Set the buffer's keymap to
  2792. ;;; be foo-mode-map, and its mode to be foo-mode.  Set the comint-mode hooks
  2793. ;;; (comint-{prompt-regexp, input-filter, input-filter-functions,
  2794. ;;; get-old-input) that need to be different from the defaults.  Call
  2795. ;;; foo-mode-hook, and you're done. Don't run the comint-mode hook yourself;
  2796. ;;; comint-mode will take care of it. The following example, from shell.el,
  2797. ;;; is typical:
  2798. ;;;
  2799. ;;; (defvar shell-mode-map '())
  2800. ;;; (cond ((not shell-mode-map)
  2801. ;;;        (setq shell-mode-map (copy-keymap comint-mode-map))
  2802. ;;;        (define-key shell-mode-map "\C-c\C-f" 'shell-forward-command)
  2803. ;;;        (define-key shell-mode-map "\C-c\C-b" 'shell-backward-command)
  2804. ;;;        (define-key shell-mode-map "\t" 'comint-dynamic-complete)
  2805. ;;;        (define-key shell-mode-map "\M-?"
  2806. ;;;          'comint-dynamic-list-filename-completions)))
  2807. ;;;
  2808. ;;; (defun shell-mode ()
  2809. ;;;   (interactive)
  2810. ;;;   (comint-mode)
  2811. ;;;   (setq comint-prompt-regexp shell-prompt-pattern)
  2812. ;;;   (setq major-mode 'shell-mode)
  2813. ;;;   (setq mode-name "Shell")
  2814. ;;;   (use-local-map shell-mode-map)
  2815. ;;;   (make-local-variable 'shell-directory-stack)
  2816. ;;;   (setq shell-directory-stack nil)
  2817. ;;;   (add-hook 'comint-input-filter-functions 'shell-directory-tracker)
  2818. ;;;   (run-hooks 'shell-mode-hook))
  2819. ;;;
  2820. ;;;
  2821. ;;; Note that make-comint is different from make-shell in that it
  2822. ;;; doesn't have a default program argument. If you give make-shell
  2823. ;;; a program name of NIL, it cleverly chooses one of explicit-shell-name,
  2824. ;;; $ESHELL, $SHELL, or /bin/sh. If you give make-comint a program argument
  2825. ;;; of NIL, it barfs. Adjust your code accordingly...
  2826. ;;;
  2827. ;;; Completion for comint-mode users
  2828. ;;;
  2829. ;;; For modes that use comint-mode, comint-dynamic-complete-functions is the
  2830. ;;; hook to add completion functions to.  Functions on this list should return
  2831. ;;; non-nil if completion occurs (i.e., further completion should not occur).
  2832. ;;; You could use comint-dynamic-simple-complete to do the bulk of the
  2833. ;;; completion job.
  2834.  
  2835.  
  2836. ;;; Do the user's customisation...
  2837.  
  2838. (defvar comint-load-hook nil
  2839.   "This hook is run when comint is loaded in.
  2840. This is a good place to put keybindings.")
  2841.  
  2842. (run-hooks 'comint-load-hook)
  2843.  
  2844.  
  2845. (provide 'comint)
  2846.  
  2847. ;;; comint.el ends here
  2848.